-2

I am javascript beginner and I want to check exactly duplicate object in array like this

array = [{name: 'Tom', email: '[email protected]'},{name: 'Pete', email: '[email protected]'}]

and then I have object object = {name: 'Tom', email: '[email protected]'}

when I push object to array like array.push(object)

I want to check if object is exactly duplicate (same value in every key) object in array (array[0])

How to ?

Marimokung
  • 123
  • 2
  • 12
  • Please provide [Minimum reproducible code](https://stackoverflow.com/help/minimal-reproducible-example) – Programming Rage Apr 30 '21 at 05:17
  • @ProgrammingRage No, I want to push object into array if in array not exist object like the one I want to push – Marimokung Apr 30 '21 at 05:23
  • Do not push the object into the array until all validation is successful. If any validation fails then just print that it is a duplicate or do whatever you intend to do. – Programming Rage Apr 30 '21 at 05:27

1 Answers1

0

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);
Som Shekhar Mukherjee
  • 4,701
  • 1
  • 12
  • 28