How to find index in an array of objects in JavaScript

#javascript #array

Last updated on May 29, 2021 by Suraj Sharma



This tutorial is based on using the ES6 Array.findIndex() method to get the first index of an item in an array of objects.


The findIndex() method accepts a callback function as its argument, which iterates through all the elements in the array until the callbackFn does not return a truthy value


Once the callbackFn returns a truthy value, the findIndex() method returns the index of the matched element; otherwise, it returns -1.


The findIndex() method is not supported in IE browsers but you can use a polyfill of Array.findIndex


Find index of an object in an array of objects


In the below example, we will find the index of an object whose one of the keys contains a given value.


const array = [
  { id: 1, city: 'Mumbai'},
  { id: 2, city: 'New York'},
  { id: 3, city: 'Toronto'},
  { id: 4, city: 'London'}
];

const notMatchedIndex = array.findIndex((obj)=>obj.city === 'Berlin');

console.log(notMatchedIndex) // -1

const matchedIndex = array.findIndex((obj)=>obj.city === 'Toronto');

console.log(notMatchedIndex) // 2


Find index of an object using Array.forEach


Array.forEach() method can be used to find the index of an object


const array = [
  { id: 1, city: 'Mumbai'},
  { id: 2, city: 'New York'},
  { id: 3, city: 'Toronto'},
  { id: 4, city: 'London'}
];

function findIndex(array, value) {
  let index = -1;

  array.forEach((obj, i) => {
    if (obj.city === value) {
      index = i;
      return;
    }
  })

  return index;
}

console.log(findIndex(array, 'London'));
 // 3


Related Solutions


Rate this post


Suraj Sharma is a Full Stack Software Engineer. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.