Reputation: 2014
What is the best way to filter data in a Map by value?
I have implemented the forEach
and then added the key-values to another Map (as it is not recommended to delete the map while iterating)
theMap.forEach((value, key) => { if (value !== 'something') { otherMap.set(key, value)}})
Is there any more efficient way to filter the Map by value? I tried using lodash
filter function but couldn't implement it...
Upvotes: 0
Views: 106
Reputation: 16281
I would do like
var m = new Map()
m.set("a", {x: 1})
m.set("b", {x: 2})
m.set("c", {x: 3})
var f = new Map([...m].filter(v => v[1].x >= 3))
where of course you can change the filter depending of your map values type
Upvotes: 0
Reputation: 161457
Probably easiest would be to create a temporary array while iterating, like
Array.from(theMap).forEach(([key, value]) => {
if (someFilterLogic) theMap.delete(key);
});
or create a new Map
instead, e.g.
theMap = new Map(Array.from(theMap).filter(([key, value]) => someFilterLogic));
Generally worrying about "efficient" with JS code is best left to a profiler. What counts as efficient varies massively between browsers and versions. Unless you've profiled and explicitly know something is a bottleneck, or have written your code with a truly incorrect algorithmic runtime, don't worry about it.
Upvotes: 3