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]
?
concat() can be used to merge multiple arrays together. But, it does not remove duplicates.
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.
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]));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With