AppDividend
Latest Code Tutorials

Javascript Array IndexOf | How to Find Index of Array in JS

1

Javascript array indexOf() is an inbuilt function that returns the first index at which the given item can be found in an array, or -1 if it is not present in an array.  Javascript array indexOf() method searches the 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

Javascript indexOf() method returns the position of the first occurrence of a specified value in a string or an array. If you want to find the position of a specified value in the string, then use the Javascript String indexOf() method.  If you’re going to find an index of the particular item in the Array, then use the Javascript array indexOf() method.

Javascript indexOf() method returns -1 if the value to search for never occurs. Note: The indexOf() method is case sensitive.

If you are a JavaScript developer, you probably familiar with the string indexOf() method on strings.

The primary functionality of Array’s indexOf is very similar to the string indexOf() method.

If the 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.

Syntax

array.indexOf(item, start)

Parameters

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.

Return Value

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

Example

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

Finding all the occurrences of an element in a specific array is a common task we face in web development. Let us take a use case where we need to find 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

Difference between for loop and indexOf()

Suppose that you have an array that represents an ordered rank of elements, and you need to find out just where a given element falls in the ranking. Without indexOf, we would need to do something like this.

// app.js

const data = [
  'Millie Bobby Brown',
  'Sadie Sink',
  'Winona Ryder'
];

for (var i = 0;
  i < data.length && data[i] !== "Sadie Sink";
  i++) {
}

let rank = i + 1;

console.log("Sadie Sink's rank is: " + rank);

See the output.

➜  es git:(master) ✗ node app
Sadie Sink's rank is: 2
➜  es git:(master) ✗

Now, with the help of Javascript indexOf() method, we no longer have to keep track of the state of our counters and array elements.

Let’s see the above example using the Javascript indexOf() method.

// app.js

const data = [
  'Millie Bobby Brown',
  'Sadie Sink',
  'Winona Ryder'
];

let index = data.indexOf('Sadie Sink');

let rank = index + 1;

console.log("Sadie Sink's rank is: " + rank);

It gives us the same output.

Javascript Array indexof object

Let’s say you want to get the index of an array that contains objects.

For that, you need to use the Javascript 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, then st is the first object that means its index is 0.

// app.js

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);

In the above example, first, we have two objects.

  1. st
  2. got

Now, we define one Array called arr and add the two objects using the Javascript push() method.

Now, we need to find the index of mike key whose value is Finn.

But, the object is st, and in the Array, it is in the first position and the array index starting with 0. So the index of mike is also 0.

So, in the output, we will get the 0 as a position of mike key and Finn value. See the output.

➜  es git:(master) ✗ node app
0
➜  es git:(master) ✗

The array indexof() method is case insensitive.

Let’s define a scenario in which we need to find the element in the Array regardless of its case sensitiveness.

For that, we can use the Javascript array findIndex() method and Javascript toLowerCase() method.

See the following code example.

// app.js

let arr = ['miLLie', 'fiNN', 'saDiE', 'caLEB', 'gaTEn'];
query = 'caleb',
pos = arr.findIndex(item => query.toLowerCase() === item.toLowerCase());
console.log(result);

In the above example, we have defined one Array, and we need to search one array item, which is defined as a query. 

Now, regardless of case sensitiveness, we need to find the item from that Array. 

So, we have used the Array findIndex() method to get the exact position of the element and return that position. See the output.

➜  es git:(master) ✗ node app
3
➜  es git:(master) ✗

We are searching for the caleb element, which has an index 3.

Browser and Node Compatibility(Version and above)

  1. Google Chrome v1
  2. Internet Explorer v3
  3. Firefox v1
  4. Edge v12
  5. Opera  
  6. Safari v1
  7. Android webview v1 
  8. Chrome for Android v18
  9. Firefox for Android v4
  10. Opera for Android 
  11. Safari on iOS v1
  12. Samsung Internet v1.0
  13. Node.js

Finally, Javascript Array indexOf() Example is over.

Recommended Posts

Javascript array find()

Javascript array lastIndexOf()

Javascript array filter()

Javascript array forEach()

Javascript array toString

1 Comment
  1. Amit Parmar says

    thanks for the guide

Leave A Reply

Your email address will not be published.

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