JavaScript Array indexOf() Method

JavaScript array indexOf() function “returns the first index at which the given item can be found in an array or -1 if it is not present”. It searches the Array for a specified item and returns its position to the calling function.

Syntax

array.indexOf(element, start)

Parameters

  1. element: The item parameter is required, and its element, which we are searching inside an array.
  2. start: The start parameter is optional. It is the position where to start the search.

Return Value

The array indexOf() function returns the integer, the index of an element in the Array.

Example 1: How to use an array.indexOf() function

let pieces = ['king', 'queen', 'rook', 'knight', 'bishop'];

console.log(pieces.indexOf('rook'));

Output

Javascript Array IndexOf Example | Array.prototype.indexOf() Tutorial

Example 2: Finding all the occurrences of an element

Finding an element’s occurrences in a specific ray is a mon task in web development. Let us take a use case where we need to see all the events of the particular item.

let indices = [];
let array = ['a', 'b', 'a', 'c', 'a', 'd'];
let element = 'a';
let ids = array.indexOf(element);

while (ids != -1) {
  indices.push(ids);
  ids = array.indexOf(element, ids + 1);
}

console.log(indices);

In the above example, we search for one item until the whole Array is not searched.

Then, if the item’s position is found, it will be inside an array and, finally, log that Array.

Array.prototype.indexOf() Tutorial

Example 3: How to get an indexof objects in an array

To get an index of an array that contains objects, you can use the “map()” method. See the following code example in which we will find the index of a mike, which is 0 basically because when we add the two objects in the Array, st is the first object, meaning its index is 0.

let st = {
  mike: 'Finn',
  el: 'Millie'
};
let got = {
  jon: 'Kit',
  khaleesi: 'Emilia'
}

let arr = [];
arr.push(st, got);
pos = arr.map(function(e) { return e.mike; }).indexOf('Finn');

console.log(pos);

Output

0

Example 4: An array indexof() method is case insensitive.

To search an element in the array regardless of its case sensitivity, use the “array findIndex()” and “toLowerCase()” methods.

let arr = ['miLLie', 'fiNN', 'saDiE', 'caLEB', 'gaTEn'];
query = 'caleb',

pos = arr.findIndex(item => query.toLowerCase() === item.toLowerCase());

console.log(result);

Output

3

Browser Compatibility

  1. Google Chrome 1 and above
  2. Edge 12 and above
  3. Firefox 1.5 and above
  4. Internet Explorer 9 and above
  5. Opera 9.5 and above
  6. Safari 3 and above

Recommended Posts

JavaScript array find()

JavaScript array lastIndexOf()

JavaScript array filter()

JavaScript array forEach()

JavaScript array toString()

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.