JavaScript Array findIndex() Method

JavaScript Array findIndex() function is used to return an index of the first element in an array that satisfies the provided testing function. If no elements satisfy the testing function, -1 is returned. This method doesn’t modify the original array.

Syntax

array.findIndex(function(currentValue, index, arr), thisValue)

Parameters

  1. function(required): It will run for every item in an array.
  2. currentValue(required): It is the value of the current item.
  3. index(optional): The index of the current element being processed in the array.
  4. arr(optional): It is the current array object.
  5. thisValue(optional): The value is to be passed to a function to be used as its “this” value.

Return value

The index of the first element in the array that passes the test. Otherwise  -1.

Visual RepresentationVisual Representation of JavaScript Array findIndex() Method

Example 1: How to use an Array findIndex() method

let ages = [3, 10, 18, 20, 7];

console.log(ages.findIndex(age => age > 10));

Output

2

The first number that is greater than 10 in the array is 18, which is located at index 2; therefore, the output is 2.

Example 2: Passing predicate Visual Representation of Passing predicate to the findIndex() method

let arr = [11, 21, 19, 29, 17, 23, 31];

index = arr.findIndex((v) => {
  return v % 2 === 0;
});

console.log(index)

Output

-1

There are no even numbers in this array, so it returns -1.

Example 3: Where the condition is satisfied with an elementVisual Representation of Where the condition is satisfied with an element

let arr = [11, 21, 19, 20, 17, 24, 31];

index = arr.findIndex((v) => {
  return v % 2 === 0;
});

console.log(index)

Output

3

The first even number in the array is 20, which is located at index 3; therefore, the output is 3.

Example 4: Using sparse array

let data = [1, , 3].findIndex((d) => d === undefined)

console.log(data);

Output

1

Example 5: Passing non-array objects

let obj = {name: 'Krunal', age: 30};

let index = obj.findIndex(item => item === 'Krunal'); 

Output

TypeError: obj.findIndex is not a function

The findIndex() method is specifically useful when more complex searching criteria are needed. It provides more flexibility than methods like indexOf() since it can handle a callback function.

Browser compatibility

  1. Google Chrome 45
  2. Edge  12
  3. Firefox 25
  4. Safari version 8
  5. Opera version 32

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.