Page 1 of 1

searching array for a value, then getting index number

Posted: October 8th, 2009, 3:41 am
by lalamax3d@gmail.com
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??

Re: searching array for a value, then getting index number

Posted: October 8th, 2009, 4:11 am
by Yenaphe
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)

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");
}



Re: searching array for a value, then getting index number

Posted: October 8th, 2009, 11:02 pm
by lalamax3d@gmail.com
thanks, it helped.