'How do I delete the first N items from an ES6 Map object without recreating the Map?
Say I want to delete the first 100 entries of a Map without recreating the map, and also do this in the most efficient way.
Let's say you have a 500 item ES6 Map Object:
let map = new Map(... 500 items)
Currently I do it like this:
const newCache = new Map(
Array.from(map).slice(100)
)
map.clear()
map = newCache
But this recreates the Map.
The other way is to run over the first 100 keys:
Array.from(map.keys())
.slice(0, 100)
.forEach(key => map.delete(key))
But it looks inefficient.
Solution 1:[1]
Get an array of the first 100 keys of the Map, then delete them.
var keys = Array.from(map.keys()).slice(0, 100);
keys.forEach(k => map.delete(k));
Or you can use a loop so you don't need to create an array to slice.
var i = 0;
for (var k of map.keys()) {
if (i++ > 100) {
break;
}
map.delete(k);
}
I created a jsperf test with your two methods and this loop. The loop is bar far the most efficient, 5 times faster than slicing the keys.
Solution 2:[2]
If your Map is very big, you may not want to pull all of the keys back just to find the first few. In that case, entries may be a better option.
let n = 2;
let map = new Map();
map.set('a', 1);
map.set('b', 2);
map.set('c', 3);
map.set('d', 4);
console.log(map) // Map(4) {'a' => 1, 'b' => 2, 'c' => 3, 'd' => 4}
let iterator = map.entries();
for (let i = 0; i < n; i++) {
let entry = iterator.next();
let key = entry.value[0];
map.delete(key);
}
console.log(map) // Map(2) {'c' => 3, 'd' => 4}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Rich Hildebrand |
