Skip to content Skip to sidebar Skip to footer

How To Deduplicate A Merged Array?

I want to merge two arrays which have some duplicated values into one array which has no duplicates. I am using concat but the result is all value. var a = [1,2,2]; var b = [1,2,3,

Solution 1:

Merge them into a Set, and turn that set back into an array:

var a = [1,2,2];
var b = [1,2,3,3];
var c = [...new Set([...a, ...b])];
console.log(c);

You can also use concat and Array.from as an alternative to spread syntax if necessary:

var a = [1,2,2];
var b = [1,2,3,3];
var c = Array.from(new Set(a.concat(b)));
console.log(c);

Solution 2:

Add both of them to a Set, which is a data structure that ignores duplicates.


Post a Comment for "How To Deduplicate A Merged Array?"