searching array for a value, then getting index number

Find out why the . goes before the /

Moderator: Paul Tuersley

Post Reply
Posts: 5
Joined: June 10th, 2008, 8:13 am

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??
Posts: 84
Joined: February 3rd, 2009, 6:30 pm
Location: Paris - France

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);
  alert("Item not found");
Posts: 5
Joined: June 10th, 2008, 8:13 am

thanks, it helped.
Post Reply