What is the best way to access the element before and after a specific element in an array using JavaScript?

I need to create a function that accepts a string input, searches for its match in an array, and then returns the previous and next elements in the array.

const array = [
      "11111",
      "22222",
      "343245",
      "5455",
      "34999",
      "34555",
    ];

When a user enters a random number, the function will determine the previous and next elements based on that input.

For instance, if the user inputs: 3499 The function will output: The previous element is 5455 and the next element is 34555.

Answer №1

Implement the Array#indexOf method to locate the position of a specific element within an array, and then retrieve neighboring elements based on this position.

var array = [
  "apple",
  "banana",
  "orange",
  "pear",
  "grape",
  "kiwi",
];

var fruit = "pear";

var idx = array.indexOf(fruit);

console.log('Next fruit:', array[idx + 1])
console.log('Previous fruit:', array[idx - 1])

Answer №2

Utilizing the "indexOf" method:

function findNextNumber(value, array){
    const index = array.indexOf(value)
    if (index && index < array.length-1){
        return array[index+1]
    }
    return null
}

array = [5, 3, 7, 8, 1, 10];
value = 7;
console.log(findNextNumber(value, array)) //8

Alternatively, you can do it in a single line like this:

previous = array.find((_, i, arr) => value === arr[i + 1]);
next = array.find((_, i, arr) => value === arr[i - 1]);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Dispose the inputpicker filter after setting the value

I am currently utilizing the "Jquery inputpicker plugin" for creating dropdown menus. More information about this plugin can be found here. To initialize my dropdown, I use the following code: $('#test').inputpicker({ data:[ {value:"1 ...

Why isn't the login redirect script working without any errors or redirection?

Struggling to develop a Greasemonkey script that can automatically fill in certain forms and then redirect to another URL once the form is submitted. // ==UserScript== // @name usersaime // @description fills data form for user and pass // @include h ...

Protractor test fails to retain variable's value

I am currently executing a protractor test to validate the existence of a record in the grid based on a specific license number. However, I have encountered an issue where the value assigned to the rowNumber variable gets lost after traversing through all ...

Elements that allow for asynchronous data submission without requiring a traditional submit button

Hey there, I could really use some help with this puzzle I'm trying to solve. Here's the situation: <ul> <li>Number: <span id="Number">123</span></li> </ul> I want to set up a connection between t ...

What is the best way to loop through a JSON property without knowing if it is an array or not?

I'm facing a challenge with an API response where the DEPARTURESEGMENT can sometimes contain only one object and other times it contains an array of objects. This variation requires different logic in my foreach-loop. Response A: { "getdeparturesr ...

The latest changes in the MongoDB route and model may result in either data deletion or an error being thrown

I've been searching for quite some time now, and I haven't found a similar issue to the one I am facing. Working on a MERN stack application with four routes, three are functioning properly. However, the fourth route and the database model are c ...

What techniques can be used to optimize the SEO of HTML generated by JavaScript? How does React.js go about achieving this

Is my webpage optimized for SEO if it was created using appendChild and innerHTML with JavaScript? Can react.js improve the SEO of a webpage? ...

Using Capybara for testing integration with asynchronous JavaScript

I am currently facing an issue with a failing Rails integration test that has me stumped. The test utilizes Capybara with Selenium as the driver. The specific problem lies in verifying that certain page content is removed after an AJAX call is made. Essen ...

Aptana - Expose the Declaration

After hearing rave reviews about Aptana being the best IDE for JavaScript, I decided to download it. I grabbed a project from GitHub, found a method call in the code, right clicked on it, and saw 'open declaration - F3'. However, when I tried bot ...

Change prompt-sync from require to import syntax

In my Node project, I have integrated the prompt-sync module. const prompt = require('prompt-sync')(); const result = prompt(message); To maintain consistency in my TypeScript code, I decided to switch from using require to import. In order to ...

Recovering antiquated submission script in JavaScript

Here is a form with input data: <form id = 'myform'> ... <td><input type="checkbox" name="supplier_aid" value="on" checked disabled >{$output.t_artikelnr}</td> <td><input type="checkbox" n ...

An advanced password checker that notifies the user of any spaces in their password

I need help fixing my JavaScript code. The program should prompt the user for a password using a dialogue box, and then validate that the input has no spaces. If a space is detected, the program should stop and display an alert saying "Invalid, contains a ...

The Vue instance methods provide a way to access and manipulate formatted properties

I am looking to implement a method that will generate the appropriate email format to be used as the href value in an anchor tag. This method should return the formatted string in the following format: "mailto:[email protected]". var facultyInformat ...

Oops! Dropzone encountered an error because no URL was provided

I am currently working on a form that includes both HTML and JavaScript code. The form looks like this: <form class="block-center" id="pdfForm" method="POST" action="form_threatment.php" enctype="multipart/form-data" style="margin-top: 30px;"> ...

Example using three.js showing issues with external resources failing to load on jsfiddle.net

Currently, I am endeavoring to make progress with this sample project: github.com/josdirksen/learning-threejs/blob/master/chapter-09/07-first-person-camera.html I have made attempts at replicating the code on my personal pages.github.io account and also m ...

Is it possible to export a constant from within a default function to a different file?

As a newcomer to React and React Native, I am looking to pass a const variable from within a function to another file. I attempted defining it outside of the function and allowing it to be modified inside the function, but encountered an invalid Hook Call ...

Ways to verify if an array is multi-dimensional

I'm in the process of writing a code to determine if n is the highest number in the array A. If it is, return True, if not, return False. However, I am struggling with how to handle the two different conditions when the value is multidimensional or un ...

How can we automatically delete a message in DiscordJS after a certain amount of time has passed?

I am inquiring about DiscordJS and have a specific question. My query is regarding how to correctly remove a message sent by the bot on Discord. Admittedly, I am new to DiscordJS so please bear with me if this is a basic question. I appreciate all respo ...

Exploring the concept of nested views in AngularJS's UI Router with multiple views integration

I am facing an issue with configuring multiple views on one page, where one view is nested within another. My code in app.js does not seem to be working properly. Below are the details: This is my index.html file <body ng-app="configuratorApp" > ...

What is the best method for concealing a specific element on the screen using ReactJS?

I'm looking for a way to have text displayed on the screen that is only hidden when a button is pressed, but I'm struggling to figure it out. I had the idea of using useState in this way: const [textVisibility, setTextVisibility] = useState(true) ...