简体   繁体   English

如何将集合转换为数组?

[英]How to convert Set to Array?

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() . Set似乎是创建具有保证唯一元素的 Arrays 的好方法,但它没有公开任何获取属性的好方法,除了生成器 [Set].values,它以mySet.values.next()的笨拙方式调用.

This would have been ok, if you could call map and similar functions on Sets.如果您可以在 Sets 上调用map和类似函数,那就没问题了。 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.我试过Array.from ,但似乎只将类数组(NodeList 和 TypedArrays?)对象转换为数组。 Another try: Object.keys does not work for Sets, and Set.prototype does not have similar static method.另一种尝试: Object.keys不适用于 Sets,并且 Set.prototype 没有类似的 static 方法。

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?比如,使用for...of或类似的?

if no such option exists, then maybe there is a nice idiomatic one-liner for doing that ?如果不存在这样的选择,那么也许有一个很好的惯用单线来做到这一点? like, using for...of , or similar ?喜欢,使用for...of还是类似的?

Indeed, there are several ways to convert a Set to an Array :实际上,有几种方法可以将Set转换为Array

Note: safer for TypeScript.注意:TypeScript 更安全。

const array = Array.from(mySet);
  • Simply spreading the Set out in an array:简单地将 Set spreading在一个数组中:

Note: Spreading a Set has issues when compiled with TypeScript (See issue #8856 ).注意:使用 TypeScript 编译时,传播 Set 会出现问题(请参阅问题 #8856 )。 It's safer to use Array.from above instead.改用上面的Array.from会更安全。

const array = [...mySet];
  • The old-fashioned way, iterating and pushing to a new array (Sets do have forEach ):老式的方式,迭代并推送到一个新数组(集合确实有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)];

via https://speakerdeck.com/anguscroll/es6-uncensored by Angus Croll通过https://speakerdeck.com/anguscroll/es6-未经审查的 Angus Croll

It turns out, we can use spread operator:事实证明,我们可以使用spread运算符:

var myArr = [...mySet];

Or, alternatively, use Array.from :或者,或者,使用Array.from

var myArr = Array.from(mySet);

Assuming you are just using Set temporarily to get unique values in an array and then converting back to an Array, try using this:假设您只是临时使用Set来获取数组中的唯一值,然后转换回数组,请尝试使用以下命令:

_.uniq([])

This relies on using underscore or lo-dash .这依赖于使用下划线lo-dash

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.这应该可以在支持 ES6 的浏览器中正常工作,或者如果您有一个正确填充上述功能的 shim。

Edit : Today you can just use what @c69 suggests:编辑:今天你可以使用@c69 的建议:

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

使用传播运算符获得您想要的结果

var arrayFromSet = [...set];

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. value1 等于 value2 => Set 中当前位置包含的值。 The same value is passed for both arguments 为两个参数传递相同的值

Worked under IE11.在IE11下工作。

Using Set and converting it to an array is very similar to copying an Array...使用Set并将其转换为数组与复制数组非常相似...

So you can use the same methods for copying an array which is very easy in ES6所以你可以使用相同的方法来复制一个数组,这在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));

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

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]结果:[1,5]

For those looking for java solution, this worked for me.对于那些寻找 java 解决方案的人来说,这对我有用。

    Set<Integer> finalset = new HashSet<>();
    
    finalset.add(1);
    finalset.add(2);

    int size = finalset.size();
    int [] result = new  int[size]; // Initializing the array that will store values from the set.
    for (int number : finalset){ // Looping through the set
        result[i++] = number; // I am assigning each number from the set to the array and incrementing the index.
    }
    return result;// I am returning an array of results
}

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.如果将数组转换为 Set 并在此之后进行从 Set 到数组的转换。 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.

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

the simplistic way to doing this这样做的简单方法

 const array = [...new Set([1,1,2,3,3,4,5])]
    console.log(array)

 function countUniqueValues(arr) { return Array.from(new Set(arr)).length } console.log(countUniqueValues([1, 2, 3, 4, 4, 4, 7, 7, 12, 12, 13]))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM