To clear all key-value pairs from a map in TypeScript, you can use the clear method. This method removes all elements from the map, leaving it empty.
We can clear all key-value pairs from a map in TypeScript using the clear method, which removes all elements from the map.
For example,
myMap
with some key-value pairs. In this example, the map has string keys and integer values.clear
method to remove all key-value pairs from the map.size
property to verify that the map is empty.const myMap: Map<string, number> = new Map([
['one', 1],
['two', 2],
['three', 3]
]);
// Clear all key-value pairs using clear method
myMap.clear();
// Print the size of the map
console.log(`Size of the map after clearing: ${myMap.size}`);
Size of the map after clearing: 0
We can use the clear method on an already empty map in TypeScript, and it will still leave the map empty.
For example,
myMap
. In this example, the map has string keys and integer values.clear
method to remove all key-value pairs from the map, even though it is already empty.size
property to verify that the map is still empty.const myMap: Map<string, number> = new Map();
// Clear the map using clear method
myMap.clear();
// Print the size of the map
console.log(`Size of the map after clearing: ${myMap.size}`);
Size of the map after clearing: 0
We can insert key-value pairs into a map and then clear all key-value pairs using the clear method.
For example,
myMap
and inserting some key-value pairs into it. In this example, the map has string keys and integer values.clear
method to remove all key-value pairs from the map.size
property to verify that the map is empty.const myMap: Map<string, number> = new Map();
myMap.set('one', 1);
myMap.set('two', 2);
myMap.set('three', 3);
// Clear all key-value pairs using clear method
myMap.clear();
// Print the size of the map
console.log(`Size of the map after clearing: ${myMap.size}`);
Size of the map after clearing: 0
In this tutorial, we learned How to Clear All Key-Value Pairs from a Map in TypeScript language with well detailed examples.