how to locate an object with a spcific key in js array

How to Locate an Object with a Specific Key in JS Array

If you have an array of objects in JavaScript and you want to find the index of the object that has a specific key, you can do so using the Array.prototype.findIndex() method.

Let's say you have an array of objects that represent books:

const books = [
  { id: 1, title: 'The Great Gatsby', author: 'F. Scott Fitzgerald' },
  { id: 2, title: 'To Kill a Mockingbird', author: 'Harper Lee' },
  { id: 3, title: '1984', author: 'George Orwell' }
]

If you want to find the index of the book with an id of 2, you can use the following code:

const index = books.findIndex(book => book.id === 2)
console.log(index) // Output: 1

The Array.prototype.findIndex() method takes a function as its argument. This function is called for each element in the array until it finds an element that satisfies the condition specified in the function. In this case, we are checking if the id of the book is equal to 2.

If the function returns true, the Array.prototype.findIndex() method returns the index of that element. If the function returns false for every element in the array, it returns -1.

You can also use the Array.prototype.find() method to find the actual object instead of its index:

const book = books.find(book => book.id === 2)
console.log(book) // Output: { id: 2, title: 'To Kill a Mockingbird', author: 'Harper Lee' }

The Array.prototype.find() method works in a similar way to the Array.prototype.findIndex() method, but it returns the element itself instead of its index.

So, these are the two ways you can locate an object with a specific key in a JavaScript array.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe