Borislav Hadzhiev
Last updated: Nov 13, 2021
Check out my new book
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 (element.name === 'Charlie') { return true; } return false; }); console.log(index); // 👉️ 2
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.
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.
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 (element.name === 'Alice' || element.name === 'Bob') { return index; } }) .filter(element => element >= 0); console.log(indexes); // 👉️ [0 , 1]
The function we passed to the Array.map method gets called with each element in the array.
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( arr.map((element, index) => { if (element.name === 'Alice' || element.name === '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.