DEV Community

aronsantha
aronsantha

Posted on

> Merging arrays (with and without duplicates)

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];
Enter fullscreen mode Exit fullscreen mode

After: Using Set to Remove Duplicates:

To include only unique elements from each array, we can use Set:

return [...new Set([...arrayOne, ...arrayTwo])];
Enter fullscreen mode Exit fullscreen mode

Let's break down how this solution works:

  1. First, we merge the two arrays using the spread operator - just like we did before:

    [...arrayOne, ...arrayTwo]

  2. Then, we wrap the result in a new Set, which removes duplicates.

    new Set([...arrayOne, ...arrayTwo])

  3. Finally, we convert the Set into an array using the spread operator.

    [...new Set([...arrayOne, ...arrayTwo])]

Top comments (0)