Languages
[Edit]
EN

TypeScript - how to use Map

2 points
Created by:
Wayne
475

In this article, we would like to show you how to use Maps in TypeScript.

1. Introduction

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

2. Create Map

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

3. Map - set, get, size method example

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

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

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

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

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

// siz of map
const size = map.size;
console.log('map size: ' + size); // map size: 3

Output:

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

Note: Run this example online here.

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:

  1. Mozilla docs - Map
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

TypeScript

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join