How to convert Set to Array?

JavascriptArraysCollectionsSyntaxEcmascript Harmony

Javascript Problem Overview


Set seems like a nice way to create Arrays with guaranteed unique elements, but it does not expose any good way to get properties, except for generator [Set].values, which is called in an awkward way of mySet.values.next().

This would have been ok, if you could call map and similar functions on Sets. But you cannot do that, as well.

I've tried Array.from, but seems to be converting only array-like (NodeList and TypedArrays ?) objects to Array. Another try: Object.keys does not work for Sets, and Set.prototype does not have similar static method.

So, the question: Is there any convenient inbuilt method for creating an Array with values of a given Set ? (Order of element does not really matter).

if no such option exists, then maybe there is a nice idiomatic one-liner for doing that ? like, using for...of, or similar ?

Javascript Solutions


Solution 1 - Javascript

> if no such option exists, then maybe there is a nice idiomatic > one-liner for doing that ? like, using for...of, or similar ?

Indeed, there are several ways to convert a Set to an Array:

Note: safer for TypeScript.

const array = Array.from(mySet);

Note: Spreading a Set has issues when compiled with TypeScript (See issue #8856). It's safer to use Array.from above instead.

const array = [...mySet];
  • The old-fashioned way, iterating and pushing to a new array (Sets do have forEach):
const array = [];
mySet.forEach(v => array.push(v));
  • Previously, using the non-standard, and now deprecated array comprehension syntax:
const array = [v for (v of mySet)];

Solution 2 - Javascript

via https://speakerdeck.com/anguscroll/es6-uncensored by Angus Croll

It turns out, we can use spread operator:

var myArr = [...mySet];

Or, alternatively, use Array.from:

var myArr = Array.from(mySet);

Solution 3 - Javascript

Assuming you are just using Set temporarily to get unique values in an array and then converting back to an Array, try using this:

_.uniq([])

This relies on using underscore or lo-dash.

Solution 4 - Javascript

Perhaps to late to the party, but you could just do the following:

const set = new Set(['a', 'b']);
const values = set.values();
const array = Array.from(values);

This should work without problems in browsers that have support for ES6 or if you have a shim that correctly polyfills the above functionality.

Edit: Today you can just use what @c69 suggests:

const set = new Set(['a', 'b']);
const array = [...set]; // or Array.from(set)

Solution 5 - Javascript

Use spread Operator to get your desired result

var arrayFromSet = [...set];

Solution 6 - Javascript

In my case the solution was:

var testSet = new Set();
var testArray = [];

testSet.add("1");
testSet.add("2");
testSet.add("2"); // duplicate item
testSet.add("3");

var someFunction = function (value1, value2, setItself) {
    testArray.push(value1);
};

testSet.forEach(someFunction);

console.log("testArray: " + testArray);

value1 equals value2 => The value contained in the the current position in the Set. The same value is passed for both arguments

Worked under IE11.

Solution 7 - Javascript

Using Set and converting it to an array is very similar to copying an Array...

So you can use the same methods for copying an array which is very easy in ES6

For example, you can use ...

Imagine you have this Set below:

const a = new Set(["Alireza", "Dezfoolian", "is", "a", "developer"]);

You can simply convert it using:

const b = [...a];

and the result is:

["Alireza", "Dezfoolian", "is", "a", "developer"]

An array and now you can use all methods that you can use for an array...

Other common ways of doing it:

const b = Array.from(a);

or using loops like:

const b = [];
a.forEach(v => b.push(v));

Solution 8 - Javascript

The code below creates a set from an array and then, using the ... operator.

var arr=[1,2,3,4,5,6,7,8,9,1,2,3,4,5,6,7,8,9,];
var set=new Set(arr);
let setarr=[...set];
console.log(setarr);

Solution 9 - Javascript

SIMPLEST ANSWER

just spread the set inside []

let mySet = new Set()
mySet.add(1)
mySet.add(5)
mySet.add(5) 
let arr = [...mySet ]

Result: [1,5]

Solution 10 - Javascript

Here is an easy way to get only unique raw values from array. If you convert the array to Set and after this, do the conversion from Set to array. This conversion works only for raw values, for objects in the array it is not valid. Try it by yourself.

    let myObj1 = {
        name: "Dany",
        age: 35,
        address: "str. My street N5"
    }

    let myObj2 = {
        name: "Dany",
        age: 35,
        address: "str. My street N5"
    }

    var myArray = [55, 44, 65, myObj1, 44, myObj2, 15, 25, 65, 30];
    console.log(myArray);

    var mySet = new Set(myArray);
    console.log(mySet);

    console.log(mySet.size === myArray.length);// !! The size differs because Set has only unique items

    let uniqueArray = [...mySet];
    console.log(uniqueArray); 
    // Here you will see your new array have only unique elements with raw 
    // values. The objects are not filtered as unique values by Set.
    // Try it by yourself.

Solution 11 - Javascript

I would prefer to start with removing duplications from an array and then try to sort. Return the 1st element from new array.

    function processData(myArray) {
        var s = new Set(myArray);
        var arr = [...s];
        return arr.sort((a,b) => b-a)[1];
    }
    
    console.log(processData([2,3,6,6,5]);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionc69View Question on Stackoverflow
Solution 1 - JavascriptadeneoView Answer on Stackoverflow
Solution 2 - Javascriptc69View Answer on Stackoverflow
Solution 3 - JavascriptaaronmgdrView Answer on Stackoverflow
Solution 4 - JavascriptRolandView Answer on Stackoverflow
Solution 5 - JavascriptVignesh MuruganView Answer on Stackoverflow
Solution 6 - Javascriptd0wnView Answer on Stackoverflow
Solution 7 - JavascriptAlirezaView Answer on Stackoverflow
Solution 8 - JavascriptEkram MallickView Answer on Stackoverflow
Solution 9 - JavascriptAljohn YamaroView Answer on Stackoverflow
Solution 10 - JavascriptzdrsoftView Answer on Stackoverflow
Solution 11 - JavascriptDrashti TrivediView Answer on Stackoverflow