Working with Map and Set

Learn the ES6 Map and Set data structures step by step, including their common operations and use cases.

🎯 Introduction

This article explains the characteristics of Map and Set, their basic operations, and typical use cases. You will learn how they address limitations of plain objects and arrays and help you write concise, efficient code.


🔍 Map: A Flexible Key-Value Collection

1. Creating a Map

Create a Map by calling its constructor.

const map = new Map();
console.log(map.size); // 0; initially empty

You can also initialize a Map with a two-dimensional array, where each inner array contains a key-value pair.

const map2 = new Map([
    ['name', 'Alex'],
    ['age', 18],
]);
console.log(map2.size); // 2
console.log(map2.get('name')); // Alex

2. Adding and Retrieving Entries

Use set(key, value) to add an entry to a Map.

const map = new Map();
map.set('color', 'red');
map.set(10, 'numeric key');
console.log(map.get('color')); // red
console.log(map.get(10)); // numeric key
Map keys can be any type, unlike object property keys, which must be strings or symbols.

3. Checking and Deleting Entries

Use has(key) to check whether a Map contains a key.

console.log(map.has('color')); // true
console.log(map.has('size')); // false

Use delete(key) to remove an entry.

map.delete('color');
console.log(map.has('color')); // false

4. Iterating over a Map

Map supports several iteration methods. A for...of loop is a common choice.

const map = new Map([
    ['a', 1],
    ['b', 2],
]);

for (const [key, value] of map) {
    console.log(key, value);
}

You can also iterate over just the keys or values:

for (const key of map.keys()) {
    console.log(key);
}

for (const value of map.values()) {
    console.log(value);
}

✨ Set: A Collection of Unique Values

1. Creating a Set

Create a Set with its constructor.

const set = new Set();
console.log(set.size); // 0

Initialize it with an array:

const set2 = new Set([1, 2, 3, 2]);
console.log(set2.size); // 3; duplicates are removed automatically

2. Adding Values

Use add(value) to add a value.

const set = new Set();
set.add(1);
set.add(2);
set.add(2); // Adding the same value again has no effect
console.log(set.size); // 2

3. Checking and Deleting Values

Use has(value) to check whether a value exists:

console.log(set.has(1)); // true
console.log(set.has(3)); // false

Use delete(value) to remove a value:

set.delete(2);
console.log(set.has(2)); // false

4. Iterating over a Set

Set supports for...of iteration:

for (const val of set) {
    console.log(val);
}

🧩 Map and Set Use Cases

Map Example: Counting String Occurrences

const words = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple'];
const map = new Map();

for (const word of words) {
    if (map.has(word)) {
        map.set(word, map.get(word) + 1);
    } else {
        map.set(word, 1);
    }
}

for (const [word, count] of map) {
    console.log(`${word}: ${count}`);
}

Set Example: Removing Duplicates from an Array

const arr = [1, 2, 3, 2, 4, 1, 5];
const set = new Set(arr);
const uniqueArr = [...set];
console.log(uniqueArr); // [1, 2, 3, 4, 5]

🧾 Summary

  • Map is a flexible key-value collection with keys of any type, useful for storing complex associations.
  • Set stores unique values, making it useful for removing duplicates and checking uniqueness.
  • Understanding their basic operations helps you write more concise, efficient code.

❓ Knowledge Check

Q1: Must Map keys be strings? No. Map keys can be any type, including objects and functions.

Q2: How does Set determine whether values are unique? It uses the SameValueZero algorithm, which treats NaN as equal to itself.

Q3: How does Map performance compare with objects? Map can perform better for frequent additions and deletions or large collections, and provides convenient iteration and size access.


🧪 Exercises

  1. Write a function that takes an array of strings and returns a Map counting each string's occurrences.
function countOccurrences(arr) {
    // Write your code here
}
  1. Write a function that takes an array and returns a new array with duplicates removed, using Set.
function removeDuplicates(arr) {
    // Write your code here
}

🎉 You now know how to work with Map and Set step by step. Keep practicing to build your skills!