Languages
[Edit]
EN

TypeScript - How to use Map?

2 points
Created by:
Marcin
2478

Map is a data structure that allows us to keep key-value pairs.

1. Create Map

let map = new Map<string, number>();

2. Map - set, get, size method example

// create map
let map = new Map<string, number>();

// set entities
map.set("Ann", 25);
map.set("Seth", 32);
map.set("Kate", 27);

// get entities
let value1 = map.get("Ann");
console.log("Ann age: " + value1); // Ann age: 25

let value2 = map.get("Seth");
console.log("Seth age: " + value2); // Seth age: 32

let value3 = map.get("Kate");
console.log("Kate age: " + value3); // Kate age: 27

// siz of map
let size = map.size;
console.log("map size: " + size); // map size: 3

Output:

Ann age: 25
Seth age: 32
Kate age: 27
map size: 3

Run this example online:

codepen

3. Most important methods of Map:

map.set() - add key-value pair to Map
map.get() - retrieve value by key from Map
map.delete() - delete key-value pair by given key from Map
map.has() - check if there is a value for given key - return true / false
map.size() - size of the map, number of key-value pairs in Map

Note about map.set() method.
In other languages or self implemented data structures to add key-value pair to Map the method is named: put, add or set.

Reference:

Mozilla docs - Map

Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.