2

[JavaScript] Union of Two Arrays

 2 years ago
source link: https://siongui.github.io/2018/03/13/javascript-set-of-all-elements-in-two-arrays/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

[JavaScript] Union of Two Arrays

March 13, 2018

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:


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK