Search by title or category tag
I think you’ll agree we often find ourselves mutating, sorting or filtering data when developing the front end of web applications.
Ive found myself often checking if the data returned from the API contains the object I need.
I’ve listed a few ways to check if an array of object contains a particular object.
- array.some() - returns a truthy value great for “does this exist”
- array.find() - returns the matching element or undefined. Great for “i need some obj’s data but i only know the id” (note: this is not supported in IE 6 - 11)
- array.findIndex() - returns 0 or -1 depeding on if the criteria passes. Also great for “does this exist” (note: this is not supported in IE 6 - 11)
- array.filter() - returns an array of elems that match the criteria. “i need a subsection of an array of objects”
array.some
If it returns a truthy value at least once, the Array.some
method short circuits and returns true
.
const people = [
{id: 1, name: 'Luke'},
{id: 2, name: 'James'},
];
const isFound = people.some(element => {
if (element.id === 1) { return true;
}
});
console.log(isFound); // 👉️ true
if (isFound) {
// object exists
}
array.find
If the condition is satisfied, then Array.find
will return the array element, otherwise it returns undefined
You should use the Array.find
method instead of Array.some
, when you need to access additional properties on the object, however note that Array.find
is not supported in IE 6-11.
// Not Supported in IE 6-11
const people = [
{id: 1, name: 'Luke'},
{id: 2, name: 'James'},
];
const person = people.find(element => {
if (element.id === 1) { return true;
}
});
console.log(person); // 👉️ { id: 1, name: 'Luke' }
if (person !== undefined) {
// object exists
}
array.findIndex
The Array.findIndex method is very similar to the Array.find
method, but returns the index of the element that satisfies the conditional check, and not the element itself.
The Array.findIndex
method returns -1
if all calls of its callback function return a falsy value.
// Not supported in IE 6-11
const people = [
{id: 1, name: 'Luke'},
{id: 2, name: 'James'},
];
const index = people.findIndex(element => {
if (element.id === 1) { return true;
}
});
console.log(index); // 👉️ 0
if (index !== -1) {
// object exists
}
array.filter
Note that the Array.filter
method returns an array with all of the elements that satisfy the condition. If we had multiple objects with id
equal to 1
, all of them would be included in the resulting array.
// Supported in IE 9-11
const people = [
{id: 1, name: 'Luke'},
{id: 2, name: 'Adam'},
];
const filteredArray = people.filter(element => {
if (element.id === 1) { return true;
}
});
console.log(filteredArray); // 👉️ [ { id: 1, name: 'Luke' } ]
if (filteredArray.length > 0) {
// object exists
}