Execute Program

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 .indexOf method gives us the index of an element.

  • >
    ['a', 'b', 'c'].indexOf('b');
    Result:
    1Pass Icon
  • 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.

  • .findIndex does 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 returns true.

  • >
    ['', 'a'].findIndex(string => string.length !== 0);
    Result:
  • >
    const users = [
    {name: 'Amir', admin: false},
    {name: 'Betty', admin: true},
    ];
    users.findIndex(user => user.admin === true);
    Result:
    1Pass Icon
  • Like .indexOf, .findIndex returns 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:
    0Pass Icon
  • The callback function passed to .findIndex gets 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:
    3Pass Icon
  • 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:
    2Pass Icon
  • If our function doesn't match any elements, .findIndex returns -1, like .indexOf does. As with .indexOf, this can be a source of bugs. Remember to check for -1!

  • >
    [false, true].findIndex(element => element === true);
    Result:
    1Pass Icon
  • >
    [false, true].findIndex(element => element === null);
    Result:
    -1Pass Icon