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}|` });
              }
           }))
  • `const found = arr.find((e => e.obj === j.obj); if (found) push` – cmgchess Apr 03 '23 at 04: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 – cmgchess Apr 03 '23 at 04:37
  • 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](https://stackoverflow.com/a/56894824/633183) for a guide on compound data equality. – Mulan Apr 04 '23 at 14:10
  • Does this answer your question? [JavaScript - merge two arrays of objects and de-duplicate based on property value](https://stackoverflow.com/questions/37057746/javascript-merge-two-arrays-of-objects-and-de-duplicate-based-on-property-valu) – pilchard Apr 09 '23 at 11:09

0 Answers0