Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the last key of a Map object

Tags:

javascript

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
like image 813
johannchopin Avatar asked Nov 22 '25 17:11

johannchopin


1 Answers

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
like image 146
Adam Azad Avatar answered Nov 24 '25 07:11

Adam Azad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!