Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to use array iteration methods on ES6 Set instances?

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?

like image 725
Andrew Eisenberg Avatar asked Mar 14 '23 07:03

Andrew Eisenberg


1 Answers

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)
like image 132
Jaromanda X Avatar answered Apr 26 '23 21:04

Jaromanda X