Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter a JavaScript Map?

Given an ES6 Map and predicate function, how do I safely delete all non-matching elements for the map?


I could not find an official API function, but I can think of two implementations. The first does not attempt to delete in-place, but instead creates a copy:

// version 1:  function filter(map, pred) {    const result = new Map();    for (let [k, v] of map) {      if (pred(k,v)) {        result.set(k, v);      }    }    return result;  }    const map = new Map().set(1,"one").set(2,"two").set(3,"three");  const even = filter(map, (k,v) => k % 2 === 0);  console.log([...even]); // Output: "[ [ 2, 'two' ] ]"

The other deletes in-place. In my tests, it works but I did not find a guarantee that modifying a map does not break the iterator (of the for-of loop):

// version 2:  function deleteIfNot(map, pred) {    for (let [k, v] of map) {      if (!pred(k,v)) {        map.delete(k);      }    }    return map;  }    const map = new Map().set(1,"one").set(2,"two").set(3,"three");  deleteIfNot(map, (k,v) => k % 2 === 0);  console.log([...map]); // Output: "[ [ 2, 'two' ] ]"

Question:

  • Is the second version (the in-place delete) correct on all platforms?
  • Is there a better way to implement an in-place filter? Maybe some official API that I missed?
like image 621
Philipp Claßen Avatar asked Feb 09 '18 13:02

Philipp Claßen


People also ask

How do you put a filter on a map?

We can filter a Map in Java 8 by converting the map. entrySet() into Stream and followed by filter() method and then finally collect it using collect() method.

How do you filter objects in JavaScript?

JavaScript's Objects are not iterable like arrays or strings, so we can't make use of the filter() method directly on an Object . filter() allows us to iterate through an array and returns only the items of that array that fit certain criteria, into a new array.


2 Answers

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]]
like image 90
Roman Avatar answered Sep 21 '22 01:09

Roman


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); } 
like image 30
Estus Flask Avatar answered Sep 21 '22 01:09

Estus Flask