How to get last element of set - JavaScript

Mo Ibra

Mo Ibra

Dec 23, 2022

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

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


Problem

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

Now let's define a set like this:

// set
const set = new Set([1, 2, 3, 4, 5]);

console.log(set);

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

Set(5) { 1, 2, 3, 4, 5 }

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.

// set
const set = new Set([1, 2, 3, 4, 5]);

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

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

Output

5

Thank you for reading

Thank you for reading my blog. 🚀

Suggestions For More Articles: