-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 ?

3
  • Please provide Minimum reproducible code Commented Apr 30, 2021 at 5:17
  • @ProgrammingRage No, I want to push object into array if in array not exist object like the one I want to push Commented Apr 30, 2021 at 5: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. Commented Apr 30, 2021 at 5:27

1 Answer 1

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);

Sign up to request clarification or add additional context in comments.

1 Comment

@Marimokung Please check if this solves your problem, do let me know if you have any issues.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.