Is there an easy way to get the last key present in a Map?
var myMap = new Map()
myMap.set('0', 'foo')
myMap.set('1', 'bar')
myMap.set('2', 'baz')
myMap.getLastKey() // 2
Currently I need a loop to get this value but it looks over-complicated:
var myMap = new Map()
myMap.set('0', 'foo')
myMap.set('1', 'bar')
myMap.set('2', 'baz')
let iterator = myMap.keys();
let mapLastValue
for (i = 0; i < myMap.size; i += 1) {
mapLastValue = iterator.next().value
}
console.log(mapLastValue) // 2
You can get the list of keys, convert it to an array, and then get the last key. Use that:
var myMap = new Map()
myMap.set('0', 'foo')
myMap.set('1', 'bar')
myMap.set('2', 'baz')
let lastKey = [...myMap.keys()].pop(); // gets the last key
console.log(myMap.get(lastKey)) // baz
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With