Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Getting the last item from a Map – a simple solution?

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.

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You can convert the Map to an array of entries, then get the last element.

const map = new Map([['a', 1], ['b', 2], ['c', 3]]);
let lastEntry = [...map].at(-1);
console.log(lastEntry);

// or only get last key/value
let lastKey = [...map.keys()].at(-1);
let lastValue = [...map.values()].at(-1);
console.log(lastKey, lastValue);

However, it’s more efficient to just iterate over the entries and keep the last one.

const map = new Map([['a', 1], ['b', 2], ['c', 3]]);
let entry; for (entry of map);
console.log(entry);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading