Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting a union of two arrays in JavaScript [duplicate]

Say I have an array of [34, 35, 45, 48, 49] and another array of [48, 55]. How can I get a resulting array of [34, 35, 45, 48, 49, 55]?

like image 635
CFNinja Avatar asked Sep 02 '10 17:09

CFNinja


People also ask

Does concat remove duplicates?

concat() can be used to merge multiple arrays together. But, it does not remove duplicates.


2 Answers

With the arrival of ES6 with sets and splat operator (at the time of being works only in Firefox, check compatibility table), you can write the following cryptic one liner:

var a = [34, 35, 45, 48, 49];  var b = [48, 55];  var union = [...new Set([...a, ...b])];  console.log(union);

Little explanation about this line: [...a, ...b] concatenates two arrays, you can use a.concat(b) as well. new Set() create a set out of it and thus your union. And the last [...x] converts it back to an array.

like image 58
Salvador Dali Avatar answered Sep 18 '22 13:09

Salvador Dali


If you don't need to keep the order, and consider 45 and "45" to be the same:

function union_arrays (x, y) {    var obj = {};    for (var i = x.length-1; i >= 0; -- i)       obj[x[i]] = x[i];    for (var i = y.length-1; i >= 0; -- i)       obj[y[i]] = y[i];    var res = []    for (var k in obj) {      if (obj.hasOwnProperty(k))  // <-- optional        res.push(obj[k]);    }    return res;  }    console.log(union_arrays([34,35,45,48,49], [44,55]));
like image 32
kennytm Avatar answered Sep 19 '22 13:09

kennytm