How to delete last element of a set - JavaScript

Mo Ibra

Mo Ibra

Dec 23, 2022

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

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


Problem

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

Now let's define a set like this:

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

console.log(set);
// Set(5) { 1, 2, 3, 4, 5 }

And we only want to delete the last element, so the output becomes like this:

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

How to solve this problem?

Fortunately, we have a built-in function that deletes elements from the set called delete.


Delete last element using delete method

We can use delete() method to delete last element of set.

Example

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

// Delete element
set.delete(5);

// Print the result:
console.log(set);

Output

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

Well, now what if I want to delete the last element and I don't know its key! What do I do?

Delete the last element of the set dynamically

Now I will answer the previous question, if you want to delete the last element and you don't know its key.

You can use Array.from() to get all the element in an array and then you can get last element easily.

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

// Array with elements
const array = Array.from(set);

// last element
const lastEle = array[array.length - 1];

// Print
console.log(lastEle);

Output

5

Now that we get the last element, we can delete it using delete.

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

// Array with elements
const array = Array.from(set);

// last element
const lastEle = array[array.length - 1];

// Delete last element by his key `[0]`
set.delete(lastEle);

// Print
console.log(set);

Output

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

Thank you for reading

Thank you for reading my blog. 🚀

Suggestions For More Articles: