113 of 264 menu

findIndex method

The findIndex method allows you to find the index of the first element according to the callback passed in the parameter. If the element is not found, then -1 is returned.

Syntax

array.findIndex(function);

Example

Let's find the index of the first even array element:

let arr = [1, 2, 3, 4, 5]; let res = arr.findIndex(function (elem){ return elem % 2 == 0; }); console.log(res);

The code execution result:

1

Example

And now let's set such conditions in the function, which will not match any element in an array:

let arr = [1, 2, 3, 4, 5]; let res = arr.findIndex(function (elem){ return elem < 0; }); console.log(res);

The code execution result:

-1

See also

  • the find method
    that searches for an element in an array
  • the findLast method
    that searches for an element from the end of an array
  • the findLastIndex method
    that searches for the index of an element from the end of an array
byenru