The indexOf()
method finds the first index for a given element.
It returns -1 if not found.
arr.indexOf(searchElement[, fromIndex])
searchElement
- element to locate in the array.fromIndex
- Optional, The index to start. Default to 0.If fromIndex
is greater than or equal to the array's length, -1 is returned.
Search an array for the item "Java":
var languages = ["CSS", "HTML", "Java", "Javascript"]; var a = languages.indexOf("Java"); console.log(a);//from ww w . j a v a 2s .c o m
Search an array for the item "Java", starting the search at position 4:
var languages = ["CSS", "HTML", "Java", "Javascript", "CSS", "HTML", "Java", "Javascript"]; var a = languages.indexOf("Java", 4); console.log(a);//from w w w . j a v a2 s.com
The following example uses indexOf()
to locate values in an array.
var array = [2, 6, 9, 9]; let a = array.indexOf(2); console.log(a);/* w w w .ja v a 2 s. c o m*/ a = array.indexOf(7); console.log(a); a = array.indexOf(6, 2); console.log(a); a = array.indexOf(2, -1); console.log(a); a = array.indexOf(2, -3); console.log(a);
Finding all the occurrences of an element
var indices = []; var array = ['a', 'b', 'a', 'c', 'a', 'd', 'e','a']; var element = 'a'; var idx = array.indexOf(element); while (idx != -1) { indices.push(idx);//from w w w . j a v a2 s . c om idx = array.indexOf(element, idx + 1); } console.log(indices);
More example
let numbers = [1, 2, 3, 4, 5, 4, 3, 2, 1]; console.log(numbers.indexOf(4)); // 3 console.log(numbers.lastIndexOf(4)); // 5 console.log(numbers.includes(4)); // true console.log(numbers.indexOf(4, 4)); // 5 console.log(numbers.lastIndexOf(4, 4)); // 3 console.log(numbers.includes(4, 7)); // false let person = {//from ww w . j a v a2 s. com name: "HTML" }; let people = [{ name: "HTML" }]; let morePeople = [person]; console.log(people.indexOf(person)); // -1 console.log(morePeople.indexOf(person)); // 0 console.log(people.includes(person)); // false console.log(morePeople.includes(person)); // true