[JavaScript] Intersection of Two Arrays
See demo first:
Array A:Array B:
Find common elements in two arrays, i.e., intersection or matches in two arrays. There are many ways to find the intersection [1] [3]. Here we will implement the method mentioned in [2].
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 yes, the item is in the intersection of the two arrays.
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="getIntersection">Get Intersection</button>
<input type="text" name="intersection"><br>
JavaScript:
var arra = document.querySelector("input[name='arra']");
var arrb = document.querySelector("input[name='arrb']");
var intersection = document.querySelector("input[name='intersection']");
var btn = document.querySelector("#getIntersection");
btn.addEventListener("click", function(e) {
var arrayA = eval(arra.value);
var arrayB = eval(arrb.value);
var arrayU = [];
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])) {
arrayU.push(arrayB[i]);
}
}
intersection.value = JSON.stringify(arrayU);
});
For the same implementation in Go, see [5].
Tested on: Chromium 64.0.3282.167 on Ubuntu 17.10 (64-bit)
References:
[1] |
[2] | efficiency - Quick algorithm to find matches between two arrays - Software Engineering Stack Exchange |
[3] |
[4] |
[5] | [Golang] Intersection of Two Arrays |