How to convert Set to Array?

前端 未结 10 1037
余生分开走
余生分开走 2020-11-28 01:04

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

相关标签:
10条回答
  • 2020-11-28 01:30

    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));
    
    0 讨论(0)
  • 2020-11-28 01:33

    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.

    0 讨论(0)
  • 2020-11-28 01:36

    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);
    
    0 讨论(0)
  • 2020-11-28 01:38

    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:

    using Array.from

    let array = Array.from(mySet);
    

    Simply spreading the Set out in an array

    let array = [...mySet];
    

    The old fashion way, iterating and pushing to a new array (Sets do have forEach)

    let array = [];
    mySet.forEach(v => array.push(v));
    

    Previously, using the non-standard, and now deprecated array comprehension syntax:

    let array = [v for (v of mySet)];
    
    0 讨论(0)
提交回复
热议问题