Today, I ran into a situation where simply merging two arrays was not enough: the new array had to only include unique values. Let's see how I tackled it.
Before: Using Spread Operator to Combine Arrays:
To merge two arrays and include all elements from both, we can use the Spread operator like this:
return [...arrayOne, ...arrayTwo];
After: Using Set to Remove Duplicates:
To include only unique elements from each array, we can use Set:
return [...new Set([...arrayOne, ...arrayTwo])];
Let's break down how this solution works:
-
First, we merge the two arrays using the spread operator - just like we did before:
[...arrayOne, ...arrayTwo]
-
Then, we wrap the result in a new Set, which removes duplicates.
new Set([...arrayOne, ...arrayTwo])
-
Finally, we convert the Set into an array using the spread operator.
[...new Set([...arrayOne, ...arrayTwo])]
Top comments (0)