The findIndex() method returns the index of the first element in an array that satisfies a provided testing function. If no elements satisfy the testing function, it returns -1.

Unlike indexOf(), which only looks for a specific value, findIndex() allows you to use complex logic to find an item.

1. Syntax

array.findIndex((element, index, array) => {
  // Return true if this is the item you are looking for
})
  • element: The current element being processed.
  • index (Optional): The index of the current element.
  • array (Optional): The array findIndex was called upon.

2. Basic Example: Finding an Object

The most common use for findIndex() is searching through an array of objects, where indexOf() would fail.

const users = [
  { id: 1, name: 'Alice' },
  { id: 2, name: 'Bob' },
  { id: 3, name: 'Charlie' }
];

// Find the index of the user with ID 2
const index = users.findIndex(user => user.id === 2);

console.log(index); // 1

3. Searching with Complex Conditions

You can find the index based on any condition, such as the first number greater than a certain value or the first string starting with a specific letter.

const scores = [10, 15, 25, 8, 30];

// Find the index of the first score that is a "pass" (e.g., 20 or higher)
const firstPass = scores.findIndex(score => score >= 20);

console.log(firstPass); // 2 (the value 25)

4. Practical Use: Updating an Item

In frameworks like React, findIndex() is often used to locate an item in a list so you can update it.

const cart = [{ item: 'Apple', qty: 1 }, { item: 'Banana', qty: 1 }];

const index = cart.findIndex(p => p.item === 'Banana');

if (index !== -1) {
  // Update the quantity of the found item
  cart[index].qty += 1;
}

5. Common Pattern: Removing an Item

Developers often use findIndex() in combination with .splice() to remove a specific object from an array.

const fruits = [{name: 'apple'}, {name: 'banana'}, {name: 'cherry'}];

const targetIndex = fruits.findIndex(f => f.name === 'banana');

if (targetIndex !== -1) {
  fruits.splice(targetIndex, 1); // Removes 1 item at targetIndex
}

Categorized in:

Javascript Array Methods,