I found some answers suggesting iterating through the Map, setting the iterated element to a variable and then reading it after the iteration. But isn’t there any better, more elegant view? I could not find a better solution so far.
Question posted in Javascript
A very good W3school tutorial can be found here.
A very good W3school tutorial can be found here.
7
Answers
Convert the Map to an array using the
Array.from()
method and then use the array index to access the last item.you can get the last item by accessing the array index
[myArray.length - 1
]You can convert the
Map
to an array of entries, then get the last element.However, it’s more efficient to just iterate over the entries and keep the last one.
With the built-in
Map
there’s no way other than iterating the entries and return what comes last. You can, however, extendMap
so that it can record its own "history", for example:convert a map to the array with spread operator and use
.pop
No, there is not. Maps are not an ordered data structure in the sense that they support indexed access – all they have is a deterministic iteration order. If you care about controlling the order of elements or accessing them by index, use an array (possibly in addition to the map).
In terms of elegance, I would recommend a helper function that takes an iterator:
then call it as
or
You could iterate the map directly and use a counter from
size
and get the last pair.