Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: Generic get next item in array

I am trying to make a JavaScript function that will search an array of strings for a value and return the next string. For example, if an array is built such that an item is followed by its stock code, I want to search for the item and have the stock code written.

var item = (from user input); //some code to get the initial item from user function findcode(code){   var arr = ["ball", "1f7g", "spoon", "2c8d", "pen", "9c3c"]; //making the array   for (var i=0; i<arr.lenth; i++){  //for loop to look through array     arr.indexOf(item);  //search array for whatever the user input was     var code = arr(i+1); //make the variable 'code' whatever comes next     break;   } } document.write(code); //write the code, I.e., whatever comes after the item 

(I'm sure it's obvious I'm new to JavaScript, and while this is similar to a number of other questions I found, those seemed to have more involved arrays or more complex searches. I can't seem to simplify them for my needs.)

like image 373
jak Avatar asked Apr 30 '13 07:04

jak


People also ask

How do you find the next index of an element in an array?

To find the position of an element in an array, you use the indexOf() method. This method returns the index of the first occurrence the element that you want to find, or -1 if the element is not found. The following illustrates the syntax of the indexOf() method.

How do you find the distinct object of an array?

One way to get distinct values from an array of JavaScript objects is to use the array's map method to get an array with the values of a property in each object. Then we can remove the duplicate values with the Set constructor. And then we can convert the set back to an array with the spread operator.


1 Answers

You've almost got it right, but the syntax is arr[x], not arr(x):

index = array.indexOf(value); if(index >= 0 && index < array.length - 1)    nextItem = array[index + 1] 

BTW, using an object instead of an array might be a better option:

data = {"ball":"1f7g", "spoon":"2c8d", "pen":"9c3c"} 

and then simply

code = data[name] 
like image 70
georg Avatar answered Oct 04 '22 18:10

georg