Back to Home
Arrays

How to Find Array Element Index

Use .findIndex() to get index of matching element

Quick Answer (2024 ES6+ Way)

javascript
const users = [
  { id: 1, name: 'Alice' },
  { id: 2, name: 'Bob' }
];
const index = users.findIndex(user => user.id === 2);
console.log(index); // 1

Live Example

javascript
const 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;
}

Common Variations

Find Last Index
javascript
const lastIndex = arr.findLastIndex(item => item > 10);
// Searches from end to start
Simple Values
javascript
const numbers = [1, 2, 3, 4, 5];
const idx = numbers.indexOf(3); // 2

❌ Don't Do This (Outdated Way)

Avoid manual loop for finding index

javascript
// DON'T DO THIS
var index = -1;
for (var i = 0; i < arr.length; i++) {
  if (arr[i].id === targetId) {
    index = i;
    break;
  }
}

Browser Support

Works in all modern browsers (ES2015+)

#array#find#index