Concat multiple arrays into one array without duplicates

You could save yourself some time and effort with the very useful utility library Lodash.

The function you're looking for is Union

As stated by Lodash:

Creates an array of unique values, in order, from all given arrays using SameValueZero for equality comparisons.

Example

_.union([2], [1, 2]);
// => [2, 1]

var a = ["1","2","3"]
  , b = ["3","4","5"]
  , c = ["4","5","6"]
  , d = [];

function newArray(x,y,z) {
  x.concat(y,z).forEach(item =>{
     if (d.indexOf(item) == -1) 
       d.push(item); 
  });
  return d;
}

console.log(newArray(a,b,c));

You can use concat() and Set together as below,

var a = ["1","2","3"];
var b = ["3","4","5"];
var c = ["4","5","6"];

var d = a.concat(b).concat(c);
var set = new Set(d);

d = Array.from(set);

console.log(d);

If your goal is to remove duplicates, you can use a set,

var arr = [1, 2, 3, 4, 5, 5, 6, 6, 6, 7]
var mySet = new Set(arr)
var filteredArray = Array.from(mySet)
console.log(filteredArray.sort()) // [1,2,3,4,5,6,7]

Tags:

Javascript