Is there a function which returns true or false when searching for an object in an array of objects?
The Array.prototype.some
method:
The some() method checks if any of the elements in an array pass a test (provided as a function). The some() method executes the function once for each element present in the array: If it finds an array element where the function returns a true value, some() returns true (and does not check the remaining values)
I'm sharing an example based on comments above, it may help others:
const listOfObjecs = [
{ id: 1, name: "Name 1", score: 11 },
{ id: 3, name: "Name 3", score: 33 },
{ id: 2, name: "Name 2", score: 22 },
{ id: 3, name: "Name 3", score: 33 },
{ id: 4, name: "Name 4", score: 44 },
{ id: 5, name: "Name 5", score: 55 },
{ id: 3, name: "Name 3", score: 33 },
];
const search1 = { id: 3, name: "Name 3", score: 33 };
const search2 = { id: 9, name: "Name 3", score: 33 };
// Using Array.prototype.some()
const resSomeSearch1 = listOfObjecs.some(item => JSON.stringify(item) === JSON.stringify(search1));
console.log(`resSome(search1): ${resSomeSearch1}`); // outputs: true
const resSomeSearch2 = listOfObjecs.some(item => JSON.stringify(item) === JSON.stringify(search2));
console.log(`resSome(search2): ${resSomeSearch2}`); // outputs: false
// Using Array.prototype.filter()
const resFilterSearch1 = !!listOfObjecs.filter(item => JSON.stringify(item) === JSON.stringify(search1)).length;
console.log(`resFilter(search1): ${resFilterSearch1}`); // outputs: true
const resFilterSearch2 = !!listOfObjecs.filter(item => JSON.stringify(item) === JSON.stringify(search2)).length;
console.log(`resFilter(search2): ${resFilterSearch2}`); // outputs: false
// Using Array.prototype.find()
const resFindSearch1 = !!listOfObjecs.find(item => JSON.stringify(item) === JSON.stringify(search1));
console.log(`resFind(search1): ${resFindSearch1}`); // outputs: true
const resFindSearch2 = !!listOfObjecs.find(item => JSON.stringify(item) === JSON.stringify(search2));
console.log(`resFind(search2): ${resFindSearch2}`); // outputs: false