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

I am using instances of ES6 Set and I need to apply some transformations to them. These are transformations 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 the result would be either a new set or an array. I would also like to use other methods for understanding the array, such as filter, map, reduce, etc. And I would also like to have similar behavior in instances of ES6 Map.

Is this possible, or do I need to use JS vanilla arrays?

+4
source share
2 answers

you can get s values ​​in an array using

Array.from(s.values())

Array.from , Array , .

Set.values ​​ Iterator, Set .

,

let s = new Set;
s.add(1);
s.add(2);
s.add(3);
let n = Array.from(s.values()).filter(val => val > 1)
+6

Array Set Map. .length [n], Set Map.

Set Array.from(s), Set Map. , - Set Map, , , , , . , , , (, ).

, .filter() Set :

Set.prototype.filter = function(fn) {
    let result = new Set();
    for (let val of this) {
       if (fn(val, this) === true) {
           result.add(val);
       }
    }
    return result;
}

let s = new Set;
s.add(1);
s.add(2);
s.add(3);
let n = s.filter(val => val > 1); 


// log the output

// log output
document.write("Set {" + Array.from(n).join(", ") +"}");
Hide result

Array.

+1

Source: https://habr.com/ru/post/1628584/


All Articles