How to delete last element of a map - JavaScript

Mo Ibra

Mo Ibra

Dec 13, 2022

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

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


Problem

Now we have a problem, which is that we want to delete the last element of a 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 to delete the last element, so the output becomes like this:

Map(1) { 'name' => 'john' }

How to solve this problem?

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


Delete last element using delete method

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

Example

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

// Delete element
map.delete('age');

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

Output

Map(1) { 'name' => 'john' }

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 map 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.

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

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

// last element
const lastEle = array[0];

// Print
console.log(lastEle);

Output

['age', 30]

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

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

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

// last element
const lastEle = array[0];

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

// Print
console.log(map);

Output

Map(1) { 'age' => 30 }

Thank you for reading

Thank you for reading my blog. 🚀

Suggestions For More Articles: