Borislav Hadzhiev
Sun Oct 17 2021·2 min read
Photo by Joshua Rawson-Harris
To get a union of two arrays:
Set
constructor to remove the
duplicates.Set
back to an array.const arr1 = ['a', 'b', 'c']; const arr2 = ['a', 'b', 'c', 'd']; const union = Array.from(new Set([...arr1, ...arr2])); // 👇️ ['a', 'b', 'c', 'd'] console.log(union);
We used the Set object to remove all the duplicates from the two arrays.
The Set
object allows us to store unique values and removes all duplicates
automatically.
If we pass it an array containing the same value multiple times, it would only
get added once to the Set
.
console.log(new Set(['a', 'a', 'a'])); // 👉️ { 'a' }
We also use the spread operator (...) to unpack the values of the two arrays into a third array.
The last step is to convert the set back to an array, using the Array.from method.
Here's an alternative, but more complicated approach.
To get a union of two arrays:
const arr1 = ['a', 'b', 'c']; const arr2 = ['a', 'b', 'c', 'd']; function getUnion(array1, array2) { const difference = array1.filter( element => !array2.includes(element) ); return [...difference, ...array2]; } // 👇️ ['a', 'b', 'c', 'd'] console.log(getUnion(arr1, arr2));
We use the filter
method to iterate over the first array and get a new array
containing only the elements that are present in the first and absent in the
second array.
The last step is to merge the difference with the values from the second array.
Set
functionality to remove the duplicates, I would definitely pick the first approach.