JavaScript Arrays: Find Index
Welcome to the Find Index lesson!
JavaScript arrays' "findIndex" method gives us the index of a value within an array.
This lesson is shown as static text below. However, it's designed to be used interactively. Click the button below to start!
We've seen that the
.indexOfmethod gives us the index of an element.>
['a', 'b', 'c'].indexOf('b');Result:
1
Sometimes we want to match a condition, rather than looking for a specific element value. For example, we might want to find the first non-empty string.
.findIndexdoes exactly that: it's like.indexOf, but it takes a function instead of an element value. The function is called on every element. We get the first element where the function returnstrue.>
['', 'a'].findIndex(string => string.length !== 0);Result:
>
const users = [{name: 'Amir', admin: false},{name: 'Betty', admin: true},];users.findIndex(user => user.admin === true);Result:
1
Like
.indexOf,.findIndexreturns the index of the first matching element, even if multiple elements match. The next example finds the index of the first 'a'.>
['a', 'b', 'a', 'b'].findIndex(string => string === 'a');Result:
0
The callback function passed to
.findIndexgets three arguments. Usually we only need the first, which is the current array element's value. Sometimes we also need the element's index, which we get as the second callback argument.The next example finds the index of the first
'a'whose index is greater than 1.>
['a', 'c', 'b', 'a'].findIndex((elem, index) => index > 1 && elem === 'a');Result:
3
The third callback argument is the entire array. This is rarely needed, but it's there just in case.
>
['a', 'b', 'c'].findIndex((element, index, array) => array[index] === 'c');Result:
2
If our function doesn't match any elements,
.findIndexreturns-1, like.indexOfdoes. As with.indexOf, this can be a source of bugs. Remember to check for-1!>
[false, true].findIndex(element => element === true);Result:
1
>
[false, true].findIndex(element => element === null);Result:
-1