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])]

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more