Get the Index of Array Element matching a Condition in JS


Borislav Hadzhiev

Last updated: Nov 13, 2021


Check out my new book

Get the Index of an Array Element with Condition #

Use the findIndex() method to get the index of an array element that matches a condition. The method takes a function and returns the index of the first element in the array, for which the condition is satisfied. If the condition is never met, the findIndex method returns -1.

const arr = [{name: 'Alice'}, {name: 'Bob'}, {name: 'Charlie'}]; // ✅ Index of first occurrence const index = arr.findIndex(element => { if ( === 'Charlie') { return true; } return false; }); console.log(index); // 👉️ 2
If you need to get all of the indexes of array elements that match a condition, scroll down to the next code snippet.

The function we passed to the Array.findIndex method gets called with each element in the array until it returns a truthy value or iterates over the entire array.

If the function returns a truthy value, the findIndex method short-circuits and returns the index of the array element.

Truthy values in JavaScript are all values that are not falsy.

The falsy values are: false, null, undefined, 0, "" (empty string), NaN (not a number).

If the callback function returns a falsy value on all iterations, the findIndex method returns -1.

In other words, if the condition was never satisfied, you will get -1 back.

Get the Indexes of all Array Elements matching a condition #

To get all indexes of array elements that match a condition, use the map() method to iterate over the array. On each iteration, check if the element matches the condition and return its index if it does. Use the filter() method to remove all undefined values from the array.

const arr = [{name: 'Alice'}, {name: 'Bob'}, {name: 'Charlie'}]; const indexes = arr .map((element, index) => { if ( === 'Alice' || === 'Bob') { return index; } }) .filter(element => element >= 0); console.log(indexes); // 👉️ [0 , 1]

The function we passed to the method gets called with each element in the array.

If the condition is met, we return the element's index, otherwise the function implicitly returns undefined.

The return value from the map method will contain the indexes of the array elements that match the condition and an undefined value for each element that doesn't.

const arr = [{name: 'Alice'}, {name: 'Bob'}, {name: 'Charlie'}]; // 👇️ [0, 1, undefined] console.log(, index) => { if ( === 'Alice' || === 'Bob') { return index; } }), );

To remove the undefined values from the array, we use the Array.filter method.

In the callback we passed to the filter() method, we check if the element is greater or equal to 0.

The filter method returns a new array that contains only the elements that match the condition, in other words all the indexes.

Further Reading #

Use the search field on my Home Page to filter through my more than 3,000 articles.