Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get a last element of ES6 Map without iterations?

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

like image 554
Kirill A. Khalitov Avatar asked Jun 18 '15 16:06

Kirill A. Khalitov


People also ask

Can a Map return null?

A map key can hold the null value. Adding a map entry with a key that matches an existing key in the map overwrites the existing entry with that key with the new entry. Map keys of type String are case-sensitive. Two keys that differ only by the case are considered unique and have corresponding distinct Map entries.


2 Answers

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();
like image 134
loganfsmyth Avatar answered Nov 26 '22 08:11

loganfsmyth


const getLastItemInMap = (map) => [...map][map.size-1];
const getLastKeyInMap = (map) => [...map][map.size-1][0];
const getLastValueInMap = (map) => [...map][map.size-1][1];
like image 29
Artem Bochkarev Avatar answered Nov 26 '22 08:11

Artem Bochkarev