I am using ES6 Set instances and I need to apply some transformations on them. These are transformations of the kind that would be simple if they were arrays. Here is an example:
let s = new Set;
s.add(1);
s.add(2);
s.add(3);
let n = s.filter(val => val > 1); // TypeError, filter not defined
let n = Array.prototype.filter.call(s, val => val > 1); // []
I was hoping that the result would either be a new Set or an array. I similarly want to use other array comprehension methods like filter
, map
, reduce
, etc. And I would also like to have similar behaviour on ES6 Map instances as well.
Is this possible, or do I need to be using vanilla JS arrays?
you can get the values of s in an array using
Array.from(s.values())
Array.from documentation states that it creates a new Array instance from an array-like or iterable object.
Set.values returns a new Iterator object that contains the values for each element in the Set object in insertion order.
So your code becomes
let s = new Set;
s.add(1);
s.add(2);
s.add(3);
let n = Array.from(s.values()).filter(val => val > 1)
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