0

We have 2 arrays containing data for objects with same key values

arr1 = [
    {"id": "qwerty1234",
    "color": "red"},
    ...
]

arr2 = [
   {"id": "qwerty1234",
    "price": 123},
    ....
]

I would like to iterate through all arr1 id values while I find the matching objects from another array arr2. I've been trying with this:

const merge = (array1, array2) => {
    array1.forEach(itm => {
        const a = array2.find(item => (item.id === itm.id))
        console.log(a.id)
    })
}

This ---console.log--- causes undefined

I think my itm.id causes the problem somehow. The comparison in find() fails even though I get right values from forEach().

In the end we could consider merging these 2 arrays by their id values.

Any ideas?

  • why you do not use the spread operator ([...arr1, arr2]) and then find duplicates in one array ? – phoenixstudio Nov 18 '20 at 11:00
  • Will not work in your case but could help https://stackoverflow.com/questions/1584370/how-to-merge-two-arrays-in-javascript-and-de-duplicate-items – phoenixstudio Nov 18 '20 at 11:02
  • Yes, `merge` does `return` the value `undefined`, but what does it log? And what error do you mention, are you saying it throws an exception? – Bergi Nov 18 '20 at 11:18
  • If you want to merge the objects by id, you should use a `Map` anyway not `find`. – Bergi Nov 18 '20 at 11:19
  • It works on the developer tools of my browser, calling `merge(arr1,arr2)` – malarres Nov 18 '20 at 12:05
  • Updated the info. @Bergi, log gives `undefined`, function itself doesn't cause exception. – veliblesku Nov 18 '20 at 14:06

1 Answers1

-1

You can use reduce to merge the two arrays. The reduce callback push in the accumulator array the current value only if accumulator array do not already includes it.

arr1.reduce( (acc,cur) => {
  if( acc.find( item => item.id === cur.id ) ) return;
  return [ ...acc, cur ];
}, arr2 )
  • Please don't post only code as answer, but also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes. – Mark Rotteveel Nov 18 '20 at 13:35
  • 1
    Why would you use concatenation? If you really wanted to do the merge using `reduce`, you'd write `arr2.reduce(…, arr1)`. – Bergi Nov 18 '20 at 15:18