Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to map/reduce/filter a Set in JavaScript?

People also ask

What is map filter reduce in JavaScript?

map creates a new array by transforming every element in an array individually. filter creates a new array by removing elements that don't belong. reduce , on the other hand, takes all of the elements in an array and reduces them into a single value.

Can we use filter in map in JavaScript?

You can chain the map(), filter() as they return the array.

What map filter reduces?

Map, Filter, and Reduce are paradigms of functional programming. They allow the programmer (you) to write simpler, shorter code, without neccessarily needing to bother about intricacies like loops and branching.

Can you map a set in JavaScript?

Any type of key is possible. Although map[key] also works, e.g. we can set map[key] = 2 , this is treating map as a plain JavaScript object, so it implies all corresponding limitations (only string/symbol keys and so on). So we should use map methods: set , get and so on. Map can also use objects as keys.


A short-hand way to do it is to convert it to an array via the ES6 spread operator.

Then all the array functions are available to you.

const mySet = new Set([1,2,3,4]);
[...mySet].reduce()

To sum up the discussion from comments: while there are no technical reasons for set to not have reduce, it's not currently provided and we can only hope it changes in ES7.

As for map, calling it alone could violate the Set constraint, so its presence here might be debatable.

Consider mapping with a function (a) => 42 - it will change the set's size to 1, and this might or might not be what you wanted.

If you're ok with violating that because e.g. you're going to fold anyway, you can apply the map part on every element just before passing them to reduce, thus accepting that the intermediate collection (which isn't a Set at this point) that's going to be reduced might have duplicated elements. This is essentially equivalent to converting to Array to do processing.


The cause of the lack of map/reduce/filter on Map/Set collections seem to be mainly conceptual concerns. Should each collection type in Javascript actually specify its own iterative methods only to allow this

const mySet = new Set([1,2,3]);
const myMap = new Map([[1,1],[2,2],[3,3]]);

mySet.map(x => x + 1);
myMap.map(([k, x]) => [k, x + 1]);

instead of

new Set(Array.from(mySet.values(), x => x + 1));
new Map(Array.from(myMap.entries(), ([k, x]) => [k, x + 1]));

An alternative were to specify map/reduce/filter as part of the iterable/iterator protocol, since entries/values/keys return Iterators. It is conceivable though that not every iterable is also "mappable". Another alternative were to specify a separate "collection protocol" for this very purpose.

However, I do not know the current discussion on this topic at ES.