Is there any way that I can insert an new element into a Map before of or after an existing key?
as for Array would be: arr.splice(<POSITION>, 0, <NEW ELEMENT>);
Thanks!
Is there any way that I can insert an new element into a Map before of or after an existing key?
as for Array would be: arr.splice(<POSITION>, 0, <NEW ELEMENT>);
Thanks!
A Map does –unlike an array– not have the semantics of “order”.
It's designed to be most efficient for storing&retrieving values for specific keys. (In fact, it's internal implementation does some structuring/ordering specifically optimized for that, “b-tree” being the keyword here.
Despite all that, mozilla docs say:
A Map object iterates its elements in insertion order — a for...of loop returns an array of [key, value] for each iteration.
update: The official ECMA-262 standard confirms this.
personally, I am guessing, implementors will keep a separate index for order-of-entry and a b-tree for most efficient singular access.
Based on this, what you would have to do is essentially, treating the map like an immutable object, and creating a new one from it:
I don't now your specific use case, but perhaps your problems could also be solved by sort Iteration to specific criteria right when iterating over it.