If you have an array of objects and and want to find a specific object inside the array, you can use the find
method to search for and return the object you’re looking for. The find
method was introduced to JavaScript in ES6.
The find
method will return the first item that passes a test callback. If no item is found, undefined
will be returned.
Let’s look at an example of how this works.
const fruits = [
{name: 'Apple', color: 'Red'},
{name: 'Apple', color: 'Green'},
{name: 'Banana', color: 'Yellow'},
{name: 'Pear', color: 'Green'},
{name: 'Orange', color: 'Orange'}
];
const banana = fruits.find(fruit => {
return fruit.name === 'Banana';
});
console.log(banana); // Outputs: {name: 'Banana', color: 'Yellow'}
const cherry = fruits.find(fruit => {
return fruit.name === 'Cherry';
});
console.log(cherry); // Outputs: undefined
const apple = fruits.find(fruit => {
return fruit.name === 'Apple';
});
console.log(apple); // Outputs: {name: 'Apple', color: 'Red'}
Using findIndex
If you’d like to find the position of index of an item in an array, you can replace find
with findIndex
.
const fruits = [
{name: 'Apple', color: 'Red'},
{name: 'Apple', color: 'Green'},
{name: 'Banana', color: 'Yellow'},
{name: 'Pear', color: 'Green'},
{name: 'Orange', color: 'Orange'}
];
const banana = fruits.findIndex(fruit => {
return fruit.name === 'Banana';
});
console.log(banana); // Outputs: 2
Leave a Reply