DEV Community

Cover image for How to convert a Set to an Array? – JavaScript
Mamun Abdullah
Mamun Abdullah

Posted on

3 2

How to convert a Set to an Array? – JavaScript

When you remove the duplicate numbers from an array with new Set() method, it turns into a set instead of an array like this

let duplicates = [1,2,3,4,5,6,2];

// remove the duplicates

let noDuplicates = new Set(duplicates);

// output Set {1,2,3,4,5,6}

Enter fullscreen mode Exit fullscreen mode

Duplicates may happen by posting/collecting same value from one/different sources, or by concat() arrays.

And you can convert that set to an array again.

Solution 1:

let duplicates = [1,2,3,4,5,6,2];

// remove the duplicates

let noDuplicates = new Set(duplicates);

// output {1,2,3,4,5,6}

let arrayWithNoDuplicates = Array.from(noDuplicates);

// output [1,2,3,4,5,6]


Enter fullscreen mode Exit fullscreen mode

Solution 2:


let duplicates = [1,2,3,4,5,6,2];

// remove the duplicates

let noDuplicates = new Set(duplicates);

// output {1,2,3,4,5,6}

let arrayWithNoDuplicates = [...noDupicates];

// output [1,2,3,4,5,6]
Enter fullscreen mode Exit fullscreen mode

Solution 3:

let duplicates = [1,2,3,4,5,6,2];

let noDuplicates = Array.from(new Set(duplicates))

// output [1,2,3,4,5,6]
Enter fullscreen mode Exit fullscreen mode

Solution 4:

let duplicates = [1,2,3,4,5,6,2];

let noDuplicates = [... new Set(duplicates)];

// output [1,2,3,4,5,6]

Enter fullscreen mode Exit fullscreen mode

Apply

let a = [1,2,3,4];
let b = [5,6,2];

let c = a.concat(b);
let d = new Set(c);
let e = Array.from(d);

// or in one line

let f = Array.from(new Set(a.concat(b)));

Enter fullscreen mode Exit fullscreen mode

Source : How to convert a Set to an Array? – JavaScript | tradecoder

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

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

👋 Kindness is contagious

Dive into an ocean of knowledge with this thought-provoking post, revered deeply within the supportive DEV Community. Developers of all levels are welcome to join and enhance our collective intelligence.

Saying a simple "thank you" can brighten someone's day. Share your gratitude in the comments below!

On DEV, sharing ideas eases our path and fortifies our community connections. Found this helpful? Sending a quick thanks to the author can be profoundly valued.

Okay