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.)
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.
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.
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With