Skip to content
Advertisement

Efficient way to merge two array of objects in javascript based on similarities?

So I have two array of objects:

var arr1 = [{id:1, name:John }{id:2, name:Adam }]

var arr2 = [{id:1, address:NY, number: 200}, {id:2, address:LA, number: 300}]

and the expected result is:

var newArr = [{id:1, name:John, address:NY, number: 200 }, { id:2, name:Adam, address:LA, number: 300}]

This is just two examples out of thousands of data, I have tried mapping through two arrays and inserting them manually however this would always result in a timeout since I think looping is quite heavy on the backend server. Is there an efficient way to do such an operation or a lightweight solution in packages like lodash to achieve this?

Advertisement

Answer

Unless you’re using native module, lodash and other packages will also loop over the values internally.

Assuming that you’re using id to group the elements together, this is probably what you want

function mergeArrays(array1, array2) {
  const groups = {};

  for (const array of [array1, array2]) {
    for (const elem of array) {
      if (!groups[elem.id]) {
        groups[elem.id] = {};
      }

      Object.assign(groups[elem.id], elem);
    }
  }

  return Object.values(groups);
}

var arr1 = [{id:1, name:'John' }, {id:2, name:'Adam' }];
var arr2 = [{id:1, address:'NY', number: 200}, {id:2, address:'LA', number: 300}]

console.log(mergeArrays(arr1, arr2));
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement