There could be MULTIPLE POSSIBLE WAYS to check if an element(in
your case its Object) is present in an array or not.
const arr = [
{ id: 1, username: 'fred' },
{ id: 2, username: 'bill' },
{ id: 3, username: 'ted' },
];
let say you want to find an object with id = 3.
1. find:
It searches for an element in an array and if it finds out then it returns that element else return undefined. It returns the value of the first element in the provided array that satisfies the provided testing function. reference
const ObjIdToFind = 5;
const isObjectPresent = arr.find((o) => o.id === ObjIdToFind);
if (!isObjectPresent) { // As find return object else undefined
arr.push({ id: arr.length + 1, username: 'Lorem ipsum' });
}
2. filter:
It searches for elements in an array and filters out all element that matches the condition. It returns a new array with all elements and if none matches the condition then an empty array. reference
const ObjIdToFind = 5;
const arrayWithFilterObjects= arr.filter((o) => o.id === ObjIdToFind);
if (!arrayWithFilterObjects.length) { // As filter return new array
arr.push({ id: arr.length + 1, username: 'Lorem ipsum' });
}
3. some:
The some() method tests whether at least one element is present in an array that passes the test implemented by the provided function. It returns a Boolean value. reference
const ObjIdToFind = 5;
const isElementPresent = arr.some((o) => o.id === ObjIdToFind);
if (!isElementPresent) { // As some return Boolean value
arr.push({ id: arr.length + 1, username: 'Lorem ipsum' });
}