0

I want to push the elements of arr2 into arr1 but it should not duplicate the elements

let arr = [{obj: "ABC"},{obj: "XYZ"},{obj: "LMN"}]
const arr2 = [{obj: "ABC"},{obj: "MNO"}]
 
arr2.forEach(j => {
           arr.find((e =>{
              if(j.obj !== e.obj){
                arr.push({ obj: `${j.obj}|` });
              }
           }))
4
  • const found = arr.find((e => e.obj === j.obj); if (found) push Commented Apr 3, 2023 at 4:33
  • 2
    another approach would be to convert arr1 values to a set and foreach arr2 checking if set has value and push if it doesnt Commented Apr 3, 2023 at 4:37
  • 2
    you actually want to avoid find because nesting two linear operations (forEach and find) results in a quadratic space-time complexity. see this Q&A for a guide on compound data equality. Commented Apr 4, 2023 at 14:10
  • Does this answer your question? JavaScript - merge two arrays of objects and de-duplicate based on property value Commented Apr 9, 2023 at 11:09

2 Answers 2

1

The find method is actually not the best way to go about this answer. To push elements from arr2 into arr without duplicating, you can check if the object already exists in arr before pushing it. Here's an updated version:

let arr = [{ obj: "ABC" }, { obj: "XYZ" }, { obj: "LMN" }];
const arr2 = [{ obj: "ABC" }, { obj: "MNO" }];

arr2.forEach((j) => {
  // Check if the object is not already in arr
  if (!arr.some((e) => e.obj === j.obj)) {
    arr.push({ obj: j.obj });
  }
});

console.log(arr);

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

Comments

0

You could use the new Set which by nature does not allows to contain duplicate values.
There's a caveat though, since we cannot compare two different instances of an Object (even if the contents are the same) - those objects must first be stringified in order for the Set values uniqueness magic to kick in:

const a1 = [{ obj: "ABC" }, { obj: "XYZ" }, { obj: "LMN" }];
const a2 = [{ obj: "ABC" }, { obj: "MNO" }];

const ob2st = o => JSON.stringify(o);
const st2ob = s => JSON.parse(s);

const mergedSet = new Set([...a1.map(ob2st), ...a2.map(ob2st)]);
const a3 = [...mergedSet].map(st2ob);

console.log(a3);

also important to notice is that the newly created objects inside our new a3 array - modifying their property values, will no longer be reflected in the original a1 and a2 objects. This practice helps to maintain data integrity.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.