Using Set
Create a Set and concatenate all values with some separator string that you're sure doesn't appear in your values (I've chosen +).
So, for this object { name: "Tom", email: "[email protected]" } we store [email protected] in the Set.
Now, while pushing again concatenate all values with the same separator string and check if this exists in the Set.
- If it does, don't push
- Otherwise push it to the array.
I've tried to push two objects in the snippet below, the first object doesn't get pushed while the second does.
Caveat
Suppose you have an object where is name is "Tom+" and email is "[email protected]" ({ name: "Tom", email: "[email protected]" }).
So we store "[email protected]" in the Set
Now suppose we want to insert an object where name is Tom and email is [email protected], which is definitely a different object from the one above.
But since we again generate the same string [email protected] to check in the Set, we don't push this object onto the array.
So, it is essential to choose the separator string wisely.
const
arr = [{ name: "Tom", email: "[email protected]" }, { name: "Pete", email: "[email protected]" }],
s = new Set(arr.map((o) => Object.values(o).join("+"))),
addNewObj = (arr, obj) => {
if (!s.has(Object.values(obj).join("+"))) {
arr.push(obj);
}
};
addNewObj(arr, { name: "Tom", email: "[email protected]" });
addNewObj(arr, { name: "John", email: "[email protected]" });
console.log(arr);