i have an array, myArr = ["apple","orange","grapes","lemon"];
i wanted to check whats index number of orange is in above array
// search element, if yes, whats the index is?
basically array is lengthy? don't wanna iterate through, check equality comparison and then sort out
any ideas??
searching array for a value, then getting index number
Moderator: Paul Tuersley
You have to do something like this:
(i'm typing the code directly, can't test it right now, so check for typos & such, but the idea is here)
(i'm typing the code directly, can't test it right now, so check for typos & such, but the idea is here)
Code: Select all
var myArr = ["apple","orange","grapes","lemon"];
var itemIndex = null;
var itemSearched = "orange";
// Loop inside the array to search for the value
for (var i = 0; i < myArr.length; i++){
if (myArr[i] == itemSearched){ // check the actual value
itemIndex = i; // Set itemIndex is the value is the same as searched
break; // Exits the loop now that the item is found
}
}
// Check if itemIndex have a value
if (itemIndex){
alert("Item found, index is: "+itemIndex);
}else{
alert("Item not found");
}
Sébastien
http://www.yenaphe.info
http://www.yenaphe.info