How to get last element of map - JavaScript

Mo Ibra

Mo Ibra

Dec 13, 2022

In this article we will learn how to get last element of map.

It is very common to get last element of map in JavaScript.


Problem

Now we have a problem, which is that we want to get the last element from the map.

Now let's define a map like this:

// Map
const map = new Map([
    ['name', 'John'],
    ['age', 30],
]);

console.log(map);
// Map(2) { 'name' => 'John', 'age' => 30 }

And we only want the last element of the map, so the output becomes like this:

[ 'age', 30 ]

How to solve this problem?

To solve this problem, we will use Array.from, because it converts the map into an array, and then we can easily fetch the last element.

Now we will explain these solutions in detail.


Get last element using Array.from method

We can use Array.from to solve this problem.

Array.from will convert the map into an array, and then we can easily get the last element.

// Map
const map = new Map([
    ['name', 'John'],
    ['age', 30],
]);

// Convert to array
const toArray = Array.from(map);

// Print the result:
console.log(toArray[toArray.length - 1]);

Output

[ 'age', 30 ]

Thank you for reading

Thank you for reading my blog. 🚀

Suggestions For More Articles: