Both lodash function unionBy
and unionWith
can solve your problem.
If your objects has unique key, unionBy
is the most elegant way to handle it.
var arr1 = [{id:1,name:'AB'},{id:2,name:'CD'}];
var arr2 = [{id:3,name:'EF'},{id:2,name:'CD'}];
var mergedWithoutDups = _.unionBy(arr1, arr2. 'id')
If your object has no unique key, use unionWith
and isEqual
instead. This will take deep comparison on all objects to remove duplicate.
var arr1 = [{id:1,name:'AB'},{id:2,name:'CD'}];
var arr2 = [{id:3,name:'EF'},{id:2,name:'CD'}];
var mergedWithoutDups = _.unionWith(arr1, arr2. _.isEqual)
$.each(arr1,(i,x)=>{ if($.grep(arr2,(y)=> x.id == y.id && x.name==y.name ).length < 1) arr2.push(x); });
something like this, hope if helps. you can use.filter
inplace of grep inang
JSON.stringify