Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to concat two arrays and remove duplicates in javascript

Tags:

javascript

I want concat following two arrays by removing duplicates without assigning to third variable:

var arr1=[{id:1,name:'AB'},{id:2,name:'CD'}];

var arr2=[{id:3,name:'EF'},{id:2,name:'CD'}];

I want arr1 like:

[{id:1,name:'AB'},{id:2,name:'CD'},{id:3,name:'EF'}]

arr1.concat(arr2);
like image 760
madhu Goud Avatar asked Dec 23 '22 01:12

madhu Goud


1 Answers

First merge two arrays then put array into a map with their ids. Then create array from map values.

var arr1=[{id:1,name:'AB'},{id:2,name:'CD'}];
var arr2=[{id:3,name:'EF'},{id:2,name:'CD'}];

arr1 = arr1.concat(arr2) // merge two arrays
let foo = new Map();
for(const tag of arr1) {
  foo.set(tag.id, tag);
}
let final = [...foo.values()]
console.log(final)
like image 196
westdabestdb Avatar answered Dec 25 '22 22:12

westdabestdb