17

Typically, you cannot safely delete items from an list while you're looping through that list. Does this concept remain true for ES6 Maps?

I tried this simple test without exceptions:

var map = new Map([['a',1],['b',2],['c',3]]);
    map.forEach((value,key,map)=>
    {
          map.delete(key);
          let str = `["${key}",${value}] was deleted. `;
          str += `map.size = ${map.size}`;
          console.log(str);
    });

It seems ok.

Update: I just read this reference from Mozilla. It is certainly doable. I'd be interested in any performance benchmarks comparing this method of deletion with other methods (on larger datasets).

Lonnie Best
  • 9,936
  • 10
  • 57
  • 97
  • 3
    You can, it's safe, see https://stackoverflow.com/questions/35940216/es6-is-it-dangerous-to-delete-elements-from-set-map-during-set-map-iteration – petronius Oct 25 '18 at 09:19

2 Answers2

6

Well I guess you're right. I am not quite familiar with the ES6 Maps, but had done a bit of research and found this blog a bit helpful where it explains about the MAPS:

https://hackernoon.com/what-you-should-know-about-es6-maps-dc66af6b9a1e

Here you will get the deleting mechanism explanation too:
Something like this:

var m = new Map()
m.set('a', 1)
m.set('b', 2)
m.delete('a'); // true
m.delete('c'); // false (key was not there to delete)

Hope this helps.

Lonnie Best
  • 9,936
  • 10
  • 57
  • 97
Jaffer Wilson
  • 7,029
  • 10
  • 62
  • 139
4

Why? If you are working with the same instance, actually you can delete. It has functions which are used for deleting an item, so you can delete.

But from the side of Optimization don't delete any item from the Map or array. Javascript engines have optimizations based on the shape of the object. If it is the same over some reference to that object, it would be optimized. Instead of this, create a new object from the filtered values of the current object.

var map =  new Map([['a',1],['b',2],['c',3]]);
map.forEach((value,key,map)=>
{
      map.delete(key);
});

console.log(map);

There are some languages ( C# ), that you can't remove items from the IEnumerable in the for each loop, because it works another way under the hood, actually it gives you only read and update access, not delete.

Lonnie Best
  • 9,936
  • 10
  • 57
  • 97
Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112
  • 4
    Another View from Java Perspective : Deleting Entries in Map in Java will iterating will create an Error .. May be he is thinking on those lines – user1428716 Sep 11 '17 at 05:56
  • 1
    *"Javascript engines have optimizations based on the shape of the object."* - this is for object properties. Map entries are not properties of the Map object; you access them via `map.get('a')`, not `map.a`. – kaya3 Jan 26 '23 at 15:21