JavaScript Array findIndex()

The JavaScript Array findIndex() method returns the index of the first array element that satisfies the provided test function or else returns -1.

The syntax of the findIndex() method is:

arr.findIndex(callback(element, index, arr),thisArg)

Here, arr is an array.


findIndex() Parameters

The findIndex() method takes in:

  • callback - Function to execute on each element of the array. It takes in:
    • element - The current element of array.
  • thisArg (optional) - Object to use as this inside callback.

Return value from findIndex()

  • Returns the index of the first element in the array that satisfies the given function.
  • Returns -1 if none of the elements satisfy the function.

Example 1: Using findIndex() method

function isEven(element) {
  return element % 2 == 0;
}

let randomArray = [1, 45, 8, 98, 7];

firstEven = randomArray.findIndex(isEven);
console.log(firstEven); // 2

// using arrow operator
firstOdd = randomArray.findIndex((element) => element % 2 == 1);
console.log(firstOdd); // 0

Output

2
0

Example 2: findIndex() with Object elements

const team = [
  { name: "Bill", age: 10 },
  { name: "Linus", age: 15 },
  { name: "Alan", age: 20 },
  { name: "Steve", age: 34 },
];

function isAdult(member) {
  return member.age >= 18;
}

console.log(team.findIndex(isAdult)); // 2

// using arrow function and deconstructing
adultMember = team.findIndex(({ age }) => age >= 18);
console.log(adultMember); // 2

// returns -1 if none satisfy the function
infantMember = team.findIndex(({ age }) => age <= 1);
console.log(infantMember); // -1

Output

2
2
-1

Recommended Reading: JavaScript Array find()