In this article we will learn how to delete an element from map.
It is very common to delete an element from map in JavaScript.
Problem
Now we have a problem, which is that we want to delete an element from the map.
Now let's define a map like this:
// set
const set = new Set([1, 2, 3, 4, 5]);
console.log(set);
And we only want to delete an element from our map, so the output becomes like this:
Set(4) { 2, 3, 4, 5 }
If we deleted first element
How to solve this problem?
Fortunately, there is already a function in the set that deletes items call delete()
, all you have to do is use the delete()
function, and pass the item you want to delete.
Delete an element using delete
method
As we said before you can use delete()
method to remove an element from set.
Example
// set
const set = new Set([1, 2, 3, 4, 5]);
// Print before deleting
console.log(set);
// Delete element
set.delete(1);
// Print after deleting
console.log(set);
Output
Set(5) { 1, 2, 3, 4, 5 }
Set(4) { 2, 3, 4, 5 }
Well, now what if I want to delete the first element and I don't know its value! What do I do?
Delete the first element of set
Now I will answer the previous question, if you want to delete the first element and you don't know its value.
You can use Array.from()
to get all the element in an array and then you can get first element easily.
// set
const set = new Set([1, 2, 3, 4, 5]);
// Array with elements
const array = Array.from(set);
// First element
const firstEle = array[0];
// Print
console.log(firstEle);
Now that we get the first 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);
// First element
const firstEle = array[0];
// Delete first element
set.delete(firstEle);
// Print
console.log(set);
Output
Set(4) { 2, 3, 4, 5 }
Thank you for reading
Thank you for reading my blog. 🚀