To remove a key-value pair from a map in JavaScript, you can use the delete method. This method allows you to remove the key-value pair associated with the specified key.
We can remove a key-value pair from a map in JavaScript using the delete method, which removes the key-value pair associated with the specified key.
For example,
myMap
with some key-value pairs. In this example, the map has string keys and integer values.delete
method to remove the key-value pair associated with the key 'two'
. The delete
method removes the key-value pair from the map.console.log
function to verify that the key-value pair has been removed.const myMap = new Map([
['one', 1],
['two', 2],
['three', 3]
]);
// Remove a key-value pair using delete method
myMap.delete('two');
// Print the contents of the map
console.log(myMap);
Map(2) { 'one' => 1, 'three' => 3 }
We can handle the case where a key is not found in a map in JavaScript using the delete method, which returns false if the key is not present.
For example,
myMap
with some key-value pairs. In this example, the map has string keys and integer values.delete
method to attempt to remove the key-value pair associated with the key 'four'
. The delete
method returns false if the key is not found.console.log
function to verify that the map is unchanged.const myMap = new Map([
['one', 1],
['two', 2],
['three', 3]
]);
// Attempt to remove a non-existent key-value pair using delete method
const result = myMap.delete('four');
// Print the result and the contents of the map
console.log(result); // false
console.log(myMap);
false Map(3) { 'one' => 1, 'two' => 2, 'three' => 3 }
We can remove multiple key-value pairs from a map in JavaScript using the delete method, which removes the key-value pairs associated with the specified keys.
For example,
myMap
with some key-value pairs. In this example, the map has string keys and integer values.delete
method to remove the key-value pairs associated with the keys 'one'
and 'three'
. The delete
method removes the key-value pairs from the map.console.log
function to verify that the key-value pairs have been removed.const myMap = new Map([
['one', 1],
['two', 2],
['three', 3]
]);
// Remove multiple key-value pairs using delete method
myMap.delete('one');
myMap.delete('three');
// Print the contents of the map
console.log(myMap);
Map(1) { 'two' => 2 }
In this tutorial, we learned How to Remove a Key-Value Pair from a Map in JavaScript language with well detailed examples.