CFNinja CFNinja - 2 months ago 6
Javascript Question

Getting a union of two arrays in JavaScript

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]
?

Answer

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;
}

alert(union_arrays([34,35,45,48,49], [44,55]));
// shows [49, 48, 45, 35, 34, 55, 44]