This article explains how to create and use a Map in Typescript. The methods provided by the Map are described with examples in Typescript. Refer to How to use a Javascript Map on how to create and use a Map in Javascript
1. Overview
The Map data type holds key-value pairs. Objects and primitive data types can be used as keys or values in Map elements. The Map maintains the original insertion order of its elements.
2. Three ways to create a Map in Typescript
2.1 Declare and initialize with Map constructor
const daysMap = new Map()
daysMap.set("day_one", "Monday")
...
2.2 Declare with Map constructor and initialize
let daysMap: Map
daysMap = new Map()
daysMap.set("day_one", "Monday")
2.3 Initialize with inline Type
var daysMap : { [key:string]:string; } = {};
daysMap = {"day_one":"Monday","day_two":"Tuesday"}
2.4 Initialize with Typedef
type daysMapType = Record;
const daysMap: daysMapType = {"day_one":"Monday","day_two":"Tuesday"}
Lets initialize a Map with the days of the week. We will use this Map to perform various operations described below.
const daysMap = new Map();
daysMap.set("day_one", "Monday");
daysMap.set("day_two", "Tuesday");
daysMap.set("day_three", "Wednesday");
daysMap.set("day_four", "Thursday");
daysMap.set("day_five", "Friday");
daysMap.set("day_six", "Saturday");
daysMap.set("day_seven", "Sunday");
3. Iterate a Typescript Map
The forEach
method accepts a callback method. For a Map, forEach calls the callback function with each element's value, key, and the instance of the map.
daysMap.forEach((value,key,map) => {
console.log(key, value)
})
daysMap.forEach((value: string, key: string, map: Map) => {
console.log(key, value, map);
});
To iterate through keys use
Array.from(daysMap.keys()).forEach(key => console.log(key));
To iterate through values use
Array.from(daysMap.values()).forEach(key => console.log(key));
3.1 Modify elements while iterating Typescript Map
The forEach
function passes the reference to the Map being iterated. Using that reference, we can modify values while iterating the Map.
daysMap.forEach(function (value, key, map) {
map.set(key, `Extra fun ${value}`)
});
daysMap.forEach(function (value: string, key: string, map: Map) {
map.set(key, `Extra fun ${value}`)
});
4. Find value by key
4.1 Using Map.get to get value by key
daysMap.get("day_one")
finds value with the key "day_one"
4.2 Find by partial key match
Finds values with keys matching the specified criteria
Key starts with:
Find keys start with the string"day_o"
daysMap.forEach(function (value, key) {
if(key.match("^day_o")){
console.log(value)//returns Monday
}
});
daysMap.forEach(function (value: string, key: string) {
if(key.match("^day_o")){
console.log(value)//returns Monday
}
});
Keys contain:
Find keys contain string"_t"
daysMap.forEach(function (value, key) {
if(key.includes("_t")){
console.log(value)//returns Tuesday,Wednesday
}
});
daysMap.forEach(function (value: string, key: string) {
if(key.includes("_t")){
console.log(value)//returns Tuesday,Wednesday
}
});
Keys ending with:
Find keys ending with string"hree"
daysMap.forEach(function (value, key) {
if(key.endsWith("hree")){
console.log(value)//returns Wednesday
}
});
daysMap.forEach(function (value: string, key: string) {
if(key.endsWith("hree")){
console.log(value)//returns Wednesday
}
});
4. Delete a Map element
4.1 Delete by the Map key
monthsMap.delete("day_one")
deletes the element with the key "day_one"
4.2 Find and delete by the partial key match
Finds values with keys matching the matching criteria and deletes the element. All the map elements with matching keys are deleted.
Key starts with:
Find keys start with string"day_o"
and delete them
daysMap.forEach(function (value, key,map) {
if(key.match("^day_o")){
map.delete(key)//deletes Monday
}
});
daysMap.forEach(function (value: string, key: string, map: Map) {
if(key.match("^day_o")){
map.delete(key)//deletes Monday
}
});
Keys contain:
Find and delete entries with keys contain string"_t"
daysMap.forEach(function (value, key, map) {
if(key.includes("_t")){
map.delete(key)//deletes Tuesday,Wednesday
}
});
daysMap.forEach(function (value: string, key: string, map: Map) {
if(key.includes("_t")){
map.delete(key)//deletes Tuesday,Wednesday
}
});
Keys ending with:
Find and delete entries with keys ending with string"hree"
daysMap.forEach(function (value, key, map) {
if(key.endsWith("hree")){
map.delete(key)//deletes Wednesday
}
});
daysMap.forEach(function (value: string, key: string, map: Map) {
if(key.endsWith("hree")){
map.delete(key)//deletes Wednesday
}
});
5. Find value by value
5.1 Find value by partial value match
Finds values that match the specified criteria. Console logs all the elements with matching search criteria.
Values start with:
Find values start with the string"Mon"
daysMap.forEach(function (value, key) {
if(value.match("^Mon")){
console.log(value)//Monday
}
});
daysMap.forEach(function (value: string, key: string) {
if(value.match("^Mon")){
console.log(value)//Monday
}
});
Values contain:
Find entries with values contain string"es"
daysMap.forEach(function (value, key) {
if(value.includes("es")){
console.log(value)//Tuesday,Wednesday
}
});
daysMap.forEach(function (value: string, key: string) {
if(value.includes("es")){
console.log(value)//Tuesday,Wednesday
}
});
Values ending with:
Find entries with values ending with string"nday"
daysMap.forEach(function (value, key) {
if(value.endsWith("nday")){
console.log(value)//Monday, Sunday
}
});
daysMap.forEach(function (value: string, key: string) {
if(value.endsWith("nday")){
console.log(value)//Monday, Sunday
}
});
6. Empty a Typescript Map
The clear method removes all the entries in a Map and empties it.
daysMap.clear();
7. Check if a key exists in a Map
has(key)
returns true if an entry with the specified key exists in the map.daysMap.has("day_one")
returns truedaysMap.has("day_zero")
returns false
8. Find the size of a Map
The size property returns the size of a map. Note that size is a property, not a method.
daysMap.size
returns 7
9. Merge two Typescript maps
const anotherDaysMap = new Map([["1","Monday"],["2","Tuesday"],["3","Wednesday"],["4","Thursday"],["5","Friday"],["6","Saturday"],["7","Sunday"]])
let mergedMap:Map = new Map([...Array.from(daysMap.entries()), ...Array.from(anotherDaysMap.entries())]);
Or
daysMap.forEach((value,key) => {
anotherDaysMap.set(key,value)
})
Note that any elements with duplicate keys will be overridden by the last map in the Map constructor.