How to filter a JavaScript Map?

Solution 1:

If we want to use .filter() iterator, we can apply a simple trick, because there is no .filter operator for ES6 Maps.The approach from Dr. Axel Rauschmayer is:

  • Convert the map into an array of [key,value] pairs.
  • Map or filter the array.
  • Convert the result back to a map.

Example:

const map0 = new Map([
  ['a', 1],
  ['b', 2],
  ['c', 3]
]);

const map1 = new Map(
  [...map0]
  .filter(([k, v]) => v < 3 )
);

console.info([...map1]); 
//[0: ["a", 1], 1: ["b", 2]]

Solution 2:

ES6 iterables have no problems when an entry is deleted inside a loop.

There is no special API that would allow to efficiently filter ES6 map entries without iterating over them.

If a map doesn't have to be immutable and should be modified in-place, creating a new map on filtering provides overhead.

There is also Map forEach, but it presumes that value will be used, too.

Since the map is being filtered only by its key, there's no use for entry object. It can be improved by iterating over map keys:

for (let k of map.keys()) {
  if (!(k % 2))
    map.delete(k);
}