Use .findIndex() to get index of matching element
const users = [
{ id: 1, name: 'Alice' },
{ id: 2, name: 'Bob' }
];
const index = users.findIndex(user => user.id === 2);
console.log(index); // 1const products = [
{ id: 101, name: 'Laptop', inStock: true },
{ id: 102, name: 'Mouse', inStock: false },
{ id: 103, name: 'Keyboard', inStock: true }
];
// Find index of out-of-stock item
const outOfStockIdx = products.findIndex(p => !p.inStock);
console.log(`Out of stock at index: ${outOfStockIdx}`);
// Update that item
if (outOfStockIdx !== -1) {
products[outOfStockIdx].inStock = true;
}const lastIndex = arr.findLastIndex(item => item > 10);
// Searches from end to startconst numbers = [1, 2, 3, 4, 5];
const idx = numbers.indexOf(3); // 2Avoid manual loop for finding index
// DON'T DO THIS
var index = -1;
for (var i = 0; i < arr.length; i++) {
if (arr[i].id === targetId) {
index = i;
break;
}
}✓ Works in all modern browsers (ES2015+)