mgicrush mgicrush - 6 months ago 9
Javascript Question

How to merge 2 arrays with objects in one?

I have 2 arrays:


  1. [{name:'test', lastname: 'test', gender:'f'},{name:'test1', lastname: 'test1', gender:'f'},{name:'test2', lastname: 'test2', gender:'m'}]

  2. [{name:'test21', lastname: 'test21', gender:'f'},{name:'test1', lastname: 'test1', gender:'f'},{name:'test2', lastname: 'test2', gender:'m'},{name:'test22', lastname: 'test22', gender:'m'}]



How to merge these in one array with unique objects (for unique check 'name')?

Answer

A combination of filter and find will work

var a = [{name:'test', lastname: 'test', gender:'f'},{name:'test1', lastname: 'test1', gender:'f'},{name:'test2', lastname: 'test2', gender:'m'}];

var b = [{name:'test21', lastname: 'test21', gender:'f'},{name:'test1', lastname: 'test1', gender:'f'},{name:'test2', lastname: 'test2', gender:'m'},{name:'test22', lastname: 'test22', gender:'m'}];

var c = a.filter(a => b.find(b => b.name === a.name) === undefined).concat(b);

console.table(c);

enter image description here


You could also make a generic uniqueByKey function

var uniqueByKey = (key, xs)=>
  xs.reduce((ys,x)=>
    ys.find(y=> y[key] === x[key]) === undefined
      ? ys.concat([x])
      : ys,
    []);

var a = [{name:'test', lastname: 'test', gender:'f'},{name:'test1', lastname: 'test1', gender:'f'},{name:'test2', lastname: 'test2', gender:'m'}];

var b = [{name:'test21', lastname: 'test21', gender:'f'},{name:'test1', lastname: 'test1', gender:'f'},{name:'test2', lastname: 'test2', gender:'m'},{name:'test22', lastname: 'test22', gender:'m'}];

var c = uniqueByKey('name', a.concat(b));

console.table(c);

enter image description here


If you're dealing with particularly large datasets, using a Set cache instead of Array.prototype.find might be better.

var uniqueByKey = (key, xs)=>
  xs.reduce(([set, ys], x)=>
    set.has(x[key])
      ? [set, ys]
      : [set.add(x[key]), ys.concat([x])]
    , [new Set, []]
  ) [1];

var a = [{name:'test', lastname: 'test', gender:'f'},{name:'test1', lastname: 'test1', gender:'f'},{name:'test2', lastname: 'test2', gender:'m'}];

var b = [{name:'test21', lastname: 'test21', gender:'f'},{name:'test1', lastname: 'test1', gender:'f'},{name:'test2', lastname: 'test2', gender:'m'},{name:'test22', lastname: 'test22', gender:'m'}];

var c = uniqueByKey('name', a.concat(b));

console.table(c);

enter image description here

Comments