AppDividend
Latest Code Tutorials

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

0

Javascript Array IndexOf Example | Array.prototype.indexOf() Tutorial is today’s topic. The indexOf() method returns a first index at which the given item can be found in an array, or -1 if it is not present in an array.  The indexOf() method searches an array for a specified item and returns its position to the calling function. The search will start at the given position, or the beginning if no start position is given, and end the search at the end of an array.

Javascript Array IndexOf Example

If an array item is present more than once, the indexOf method returns the position of the first occurrence. The first element has position 0; the second element has position 1, and so on. The syntax of javascript array indexOf() method is following.

array.indexOf(item, start)

The item parameter is required and its element which we are searching inside an array.

The start parameter is optional. It is the position where to start the search.

Let us take a simple example by creating a file called the app.js and add the following code.

// app.js

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

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

 

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

The indexOf() compares searchElement to elements of the Array using strict equality (the same method used by the === or triple-equals operator).

Finding all the occurrences of an element

Let us take a scenario where we need to find the all the events of the particular item.

// app.js

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. If the item’s position is found, then it will that position inside an array and finally log that array.

 

Array.prototype.indexOf() Tutorial

Finally, Javascript Array IndexOf Example | Array.prototype.indexOf() Tutorial is over.

Leave A Reply

Your email address will not be published.

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