Home > Software engineering >  Efficient way to merge two array of objects in javascript based on similarities?
Efficient way to merge two array of objects in javascript based on similarities?

Time:06-21

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?

CodePudding user response:

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

CodePudding user response:

why use Librarie if you can achieve with core javascript

var a1 = [{id:1, name:'John' },{id:2, name:'Adam' }, {id: 3, name: 'mohit'}]

var a2 = [{id:1, address:'NY', number: 200}, {id:2, address:'LA', number: 300}, {id: 4, name:'dj', value: 'pj'}, {id: 5}]

let a3 = [...a1, ...a2].reduce((acc, x) => {
    acc[x.id] = Object.assign(acc[x.id] || {}, x);
    return acc;
}, {});
console.log('your need', Object.values(a3))

  • Related