31

How to get a last element of ES6 Map/Set without iterations(forEach or for of) pass through a full length of the container?

Kirill A. Khalitov
  • 1,225
  • 4
  • 16
  • 24

2 Answers2

56

Maps are iterable and ordered, but they are not arrays so they don't have any indexed access. Iterating to the final element is the best you can do. The simplest case being

 Array.from(map.values()).pop();
loganfsmyth
  • 156,129
  • 30
  • 331
  • 251
  • 7
    the question required no iterations and It seemed to me it was out of performance concerns. If that's the case, this answer is not really better than manually iterating as creating an Array out of an iterator does just that under the hood. That said, it's probably the terser way to do it. – AlexG Nov 27 '20 at 22:12
6
const getLastItemInMap = (map) => [...map][map.size-1];
const getLastKeyInMap = (map) => [...map][map.size-1][0];
const getLastValueInMap = (map) => [...map][map.size-1][1];
Artem Bochkarev
  • 1,242
  • 13
  • 23
  • 6
    You should add comments or a description to your answers as it may not be clear to others reading it. – Michael Jul 14 '20 at 17:20
  • While useful, all of these methods require iterations. [...map] converts the map into an array by... iterating over it. So if performance is a concern, you aren't saving anything this way. I think loganfsmyth is correct: iterating at least once is the best you can do when trying to retrieve an item by (insertion) "index" – Dtipson Dec 01 '21 at 03:55
  • I used this and it is apparently a bit less resource intensive: ```let lastKeyInMap = Array.from(this.myMap.keys()).pop();``` . See also here: https://gist.github.com/tizmagik/19ba6516064a046a37aff57c7c65c9cd – MikhailRatner Jan 24 '22 at 12:53