Search Methods in Javascript array
Description
Javascript array has two methods for search: indexOf() and lastIndexOf().
They both accept two arguments: the item to look for and an optional index from which to start looking.
indexOf() searches from array start while lastIndexOf() searches from the last item and continues to the front.
They will return the position of the item or -1 if the item isn't in the array.
An identity comparison (===) is used during comparing.
Example
var numbers = [1,2,3,4,5,6,5,4,3,2,1];
/* ww w . j a va 2 s. c o m*/
console.log(numbers.indexOf(4));
console.log(numbers.lastIndexOf(4));
console.log(numbers.indexOf(4, 4));
console.log(numbers.lastIndexOf(4, 4));
var person = { name: "A" };
var people = [{ name: "A" }];
var morePeople = [person];
console.log(people.indexOf(person));
console.log(morePeople.indexOf(person));
The code above generates the following result.