How To Find Value In Array Of Objects In JavaScript

JavaScript

21/06/2021


Assume you've got an array of objects containing fruits.

JAVASCRIPT
const fruits = [
{ id: 1, title: 'Orange' },
{ id: 2, title: 'Banana' },
{ id: 3, title: 'Apple' },
]

And let's suppose you want to find the element containing Banana ๐ŸŒ. There are 2 ways you can go about this problem, that I recommend.

Array.find()

The find method iterates through every element of an array (similar to map or forEach) and evaluates a statement you defined. If the statement is ever true, the iteration is stopped and that exact element is returned from the function.

JAVASCRIPT
const bananaObject = fruits.find(element => element.title === 'Banana')
console.log(bananaObject) // Object { id: 2, title: "Banana" }

Array.findIndex()

If you aren't interested in retrieving the element, but rather knowing if it exists, findIndex is your friend. ๐Ÿ˜‹ It behaves the same way as find, but returns the index of the matching element (or -1 if not found).

JAVASCRIPT
const bananaIndex = fruits.findIndex(element => element.title === 'Banana')
console.log(bananaIndex) // 1

WRITTEN BY

Code and stuff