When working with an array in JavaScript, we may need to locate a single item within the collection, there are various ways to achieve this but I will demonstrate two methods here.
We have an array named charactersArray
const charactersArray = [{
id: 1,
name: 'Katara'
}, {
id: 2,
name: 'Aang'
}, {
id: 3,
name: 'Zuko'
}, {
id: 4,
name: 'Sokka'
}];
We need a character with id of 3
.find()
The find method returns the first element that meets the given condition.
const item = characters.find((character) => character.id === 3);
// output: {id: 3, name: "Zuko"}
.filter()
The filter method creates a new array with all elements that meet the given condition.
charactersArray.filter(function(character) {
return character.id === 3
});
// output: [{id: 3, name: "Zuko"}]