There doesn't seem to be an easy and elegant way of converting a Javascript Set
to an array.
var set = new Set();
set.add("Hello");
set.add("There");
set.add(complexObject);
var setConvertedToArray = convertSetToArray(set);
console.log( setConvertedToArray ); // ["Hello", "There", ►Object ]
A map
feels about right, but the Set
prototype only has a forEach
.
Yuck:
function convertSetToArray(set) {
var a = [];
set.forEach( x => a.push(x) );
return a;
}
Anyone know of a nice way to convert a Set
to an array?
To duplicate an array, just return the element in your map call. numbers = [1, 2, 3]; numbersCopy = numbers. map((x) => x); If you'd like to be a bit more mathematical, (x) => x is called identity.
With ES6, we have a javascript Set object which stores only unique elements. A Set object can be created with array values by directly supplying the array to its constructor. If the array has duplicate values, then they will be removed by the Set. This means that the Set will only contain unique array elements.
Some ways to do it:
[...set];
[...set.keys()];
[...set.values()];
Array.from(set);
Array.from(set.keys());
Array.from(set.values());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With