One way to do this is by taking advantage of the use of dictionaries in Javascript. Dictionaries are objects in Javascript, and they are used to store key-value pairs. The keys are unique, so if you add a key that already exists, it will overwrite the previous value. This is useful for finding the union of two arrays, because you can add all the elements of the first array to a dictionary, and then add all the elements of the second array to the dictionary. The dictionary will only contain unique elements, so the union of the two arrays will be the keys of the dictionary.
// Javascript code to find the union of two arrays
function array_union(arr1, arr2) {
// Create a new dictionary
var union = {};
// Loop through the first array
for (var i = 0; i < arr1.length; i++) {
// Add the element to the dictionary
union[arr1[i]] = true;
}
// Loop through the second array
for (var i = 0; i < arr2.length; i++) {
// Add the element to the dictionary
union[arr2[i]] = true;
}
// Return the dictionary keys
return Object.keys(union);
}
If you do not want to use dictionaries, you can use this naive approach:
function array_union(arr1, arr2) {
// Create a new array
var union = [];
// Loop through the first array
for (var i = 0; i < arr1.length; i++) {
// Check if the element is in the union array
if (union.indexOf(arr1[i]) == -1) {
// Add the element to the union array
union.push(arr1[i]);
}
}
// Loop through the second array
for (var i = 0; i < arr2.length; i++) {
// Check if the element is in the union array
if (union.indexOf(arr2[i]) == -1) {
// Add the element to the union array
union.push(arr2[i]);
}
}
// Return the union array
return union;
}
Finally, the "cool kids" way to do this is by using the reduce function. This is a very powerful function that can be used to perform a reduction on an array (checkout this explanation) . In this case, we are using it to create a new array where items are only added if they are not already in the array.
function array_union(n, m) {
// Do a reduction on the two arrays to create a new array where items are only added if they are not already in the array
let union = n.concat(m).reduce((a, b) => {
if (a.indexOf(b) == -1) {
a.push(b);
}
return a;
}, []);
return union;
}