[JavaScript] Union of Two Arrays


See demo first:

Array A:
Array B:


Find the set of all elements in two arrays, i.e., union of two arrays. This is the continued work of my post yesterday [1], which is intersection of two arrays.

The idea is to convert one array to the data structure of key-value pairs, i.e., hash table. The hash table in JavaScript is built-in object type. Then we check if items of the other array is in the hash table. If not, append the item to the first array, and return the first array after finish.

The following is the code for the demo:

HTML:

Array A: <input type="text" name="arra" value="[1, 2, 3, 4, 5]"><br>
Array B: <input type="text" name="arrb" value="[2, 3, 5, 7, 11]"><br>
<br>
<button type="button" id="getUnion">Get Union</button>
<input type="text" name="union"><br>

JavaScript:

var arra = document.querySelector("input[name='arra']");
var arrb = document.querySelector("input[name='arrb']");
var union = document.querySelector("input[name='union']");
var btn = document.querySelector("#getUnion");

btn.addEventListener("click", function(e) {
  var arrayA = eval(arra.value);
  var arrayB = eval(arrb.value);

  var hashTable = {};
  for (var i = 0; i < arrayA.length; i++) {
    hashTable[arrayA[i]] = true;
  }

  for (var i = 0; i < arrayB.length; i++) {
    if (!hashTable.hasOwnProperty(arrayB[i])) {
      arrayA.push(arrayB[i]);
    }
  }

  union.value = JSON.stringify(arrayA);
});

Tested on: Chromium 64.0.3282.167 on Ubuntu 17.10 (64-bit)


References:

[1][JavaScript] Intersection of Two Arrays