How to filter a JavaScript Map?

If we want to use .filter() iterator for a map, 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]]

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)