JavaScript Array.indexOf() Method Example

The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.

Syntax

arr.indexOf(searchElement[, fromIndex])
  • search - Element to locate in the array.
  • fromIndex (Optional) - The index to start the search at. If the index is greater than or equal to the array's length, -1 is returned, which means the array will not be searched.

Examples

Example 1: Simple Array indexOf() method example

var progLangs = ['C', 'C++', 'Java', 'PHP', 'Python'];

console.log(progLangs.indexOf('C'));

// start from index 2
console.log(progLangs.indexOf('PHP', 2));

console.log(progLangs.indexOf('Python'));
Output:
0
3
4

Example 2: Locate values in an array using indexOf() method

var array = [2, 9, 9];
console.log(array.indexOf(2));     
console.log(array.indexOf(7));     
console.log(array.indexOf(9, 2));  
console.log(array.indexOf(2, -1)); 
console.log(array.indexOf(2, -3)); 
Output:
0
-1
2
-1
0

Example 3: Finding all the occurrences of an element

var indices = [];
var array = ['a', 'b', 'a', 'c', 'a', 'd'];
var element = 'a';
var idx = array.indexOf(element);
while (idx != -1) {
  indices.push(idx);
  idx = array.indexOf(element, idx + 1);
}
console.log(indices);
Output:
[0, 2, 4]

Comments

Post a Comment