findIndex()
The JavaScript findIndex() method loops over an array, returning the index position of the first element which passes a test. This test is set with a provided function, if no matching elements are found, -1 is returned.
Unlike indexOf(), findIndex() works with complex conditions and is ideal for searching arrays of objects.
Syntax
const index = array.findIndex(function(element, index, array) {
// return true when element matches
});
Parameters:
- function: A function to run for each element in the array. It takes three arguments:
- element: The current array element being processed.
- index (optional): The index of the current element.
- array (optional): The original array
findIndex()was called on.
Basic usage
The findIndex() method is perfect for locating items in arrays of objects. The following example demonstrates a found and not-found value in the array:
Loading code...
const pizzaMenu = [
{ name: 'Margherita', price: 10, available: true },
{ name: 'Pepperoni', price: 12, available: true },
{ name: 'Hawaiian', price: 13, available: false },
{ name: 'Veggie Supreme', price: 14, available: true }
];
const pepperoniIndex = pizzaMenu.findIndex(pizza => pizza.name === 'Pepperoni');
console.log(pepperoniIndex); // Output: 1
const bbqChickenIndex = pizzaMenu.findIndex(pizza => pizza.name === 'BBQ Chicken');
console.log(bbqChickenIndex); // Output: -1 (not found)
Here's an example finding the first pizza under a certain price:
Loading code...
const pizzaMenu = [
{ name: 'Supreme', price: 16 },
{ name: 'Meat Feast', price: 15 },
{ name: 'Margherita', price: 10 },
{ name: 'Pepperoni', price: 12 }
];
const affordableIndex = pizzaMenu.findIndex(pizza => pizza.price < 12);
console.log(affordableIndex);
// Output: 2 (Margherita at index position 2 is the first one under $12)
Using the index parameter
The second parameter provides access to the current index during iteration:
Loading code...
const pizzaQueue = [
{ orderId: 'A100', status: 'ready' },
{ orderId: 'A101', status: 'preparing' },
{ orderId: 'A102', status: 'preparing' },
{ orderId: 'A103', status: 'ready' }
];
// Find first order still being prepared after position 1
const nextPreparing = pizzaQueue.findIndex((order, idx) => {
return idx > 0 && order.status === 'preparing';
});
console.log(nextPreparing); // Output: 1
The function can also be extracted for readability and reuse:
Loading code...
const pizzaMenu = [
{ name: 'Margherita', price: 10, isSpicy: false },
{ name: 'Pepperoni', price: 12, isSpicy: false },
{ name: 'Diavola', price: 14, isSpicy: true },
{ name: 'Inferno', price: 15, isSpicy: true }
];
const isSpicyPizza = (pizza) => pizza.isSpicy === true;
const firstSpicyIndex = pizzaMenu.findIndex(isSpicyPizza);
console.log(firstSpicyIndex);
// Output: 2
console.log(`First spicy pizza found: ${pizzaMenu[firstSpicyIndex].name}`);
// Output: First spicy pizza found: Diavola
Searching with multiple conditions
The findIndex() method is ideal when you need to match multiple conditions. This example finds the first large pizza in stock under $15:
Loading code...
const pizzaInventory = [
{ name: 'Margherita', size: 'Large', inStock: true, price: 14 },
{ name: 'Pepperoni', size: 'Medium', inStock: false, price: 12 },
{ name: 'Veggie', size: 'Large', inStock: true, price: 15 },
{ name: 'Hawaiian', size: 'Large', inStock: true, price: 13 }
];
const matchIndex = pizzaInventory.findIndex(pizza =>
pizza.size === 'Large' &&
pizza.inStock === true &&
pizza.price < 15
);
if (matchIndex !== -1) {
console.log(`Found: ${pizzaInventory[matchIndex].name} at position ${matchIndex}`);
} else {
console.log('No matching pizza found');
}
Updating array elements
A common findIndex() use case is to locate and update an item:
Loading code...
const orders = [
{ id: 1, pizza: 'Margherita', status: 'pending' },
{ id: 2, pizza: 'Pepperoni', status: 'pending' },
{ id: 3, pizza: 'Hawaiian', status: 'pending' }
];
const updateOrderStatus = (orderId, newStatus) => {
const orderIndex = orders.findIndex(order => order.id === orderId);
if (orderIndex !== -1) {
orders[orderIndex].status = newStatus;
return `Order ${orderId} updated to: ${newStatus}`;
}
return `Order ${orderId} not found`;
};
console.log(updateOrderStatus(2, 'preparing'));
console.log(orders[1]);
When to use findIndex() vs. other methods
Use findIndex() when:
- You need the position of an object that matches specific criteria.
- Your search involves multiple conditions or complex logic.
- You intend to update or remove the found element.
Consider using other methods when:
- You're searching for primitive values (use
indexOf()). - You need all matching elements (use
filter()). - You need the found element, not its index position (use
find()). - You only need to know if a match exists (use
some()).
Conclusion
The JavaScript findIndex() method is used when you need to locate elements in arrays using custom conditions. Retruning the index of the first matching element or -1 if no match is found. Ideal for when you need to update, remove, or reference elements by their index position.