Skip to main content

Command Palette

Search for a command to run...

πŸ—‚οΈ Map, WeakMap, Set & WeakSet in JavaScript β€” Complete Guide

πŸ—‚οΈ Map, WeakMap, Set & WeakSet in JavaScript

Published
β€’7 min read
πŸ—‚οΈ Map, WeakMap, Set & WeakSet in JavaScript β€” Complete Guide

Modern JavaScript provides powerful data structures for managing collections and key-value pairs.
Understanding Map, WeakMap, Set, and WeakSet is crucial for efficient code, memory management, and solving algorithmic problems.

In this blog, we’ll cover:

  • πŸ”Ή Set

  • πŸ”Ή Map

  • πŸ”Ή WeakMap

  • πŸ”Ή WeakSet

  • πŸ”Ή Practice Questions Using These Structures


πŸ”Ή Set in JavaScript

A Set is a collection of unique values.
It automatically removes duplicates and allows fast lookup.

Example:

// Creating a Set
const mySet = new Set();

// Adding values
mySet.add(1);
mySet.add("hello");
mySet.add(true);

// Checking if a value exists
console.log(mySet.has(1)); // true

// Removing a value
mySet.delete("hello");

// Iterating through a Set
for (const value of mySet) {
    console.log(value);
}

// Size of the Set
console.log(mySet.size); // 2

// Clearing all values
mySet.clear();

βœ… Key Points

  • Stores unique values

  • Iterable with for...of

  • Provides fast add, delete, has operations

  • No duplicate values


πŸ”Ή Map in JavaScript

A Map is a collection of key-value pairs.
Unlike objects, keys can be of any type (including objects).

Example:

// Creating a Map
const myMap = new Map();

// Adding key-value pairs
myMap.set("name", "Vishal");
myMap.set("age", 21);

// Getting a value
console.log(myMap.get("name")); // Vishal

// Checking if a key exists
console.log(myMap.has("age")); // true

// Removing a key-value pair
myMap.delete("age");

// Iterating through Map
for (const [key, value] of myMap) {
    console.log(key, value);
}

// Size of the Map
console.log(myMap.size); // 1

// Clearing all entries
myMap.clear();

βœ… Key Points

  • Keys can be any type

  • Maintains insertion order

  • Supports easy iteration


πŸ”Ή WeakMap in JavaScript

A WeakMap is similar to Map but keys must be objects and are weakly referenced.
This means if there are no other references to the object, it can be garbage collected.

Example:

let obj = { key: 'value' };

// Creating a WeakMap
let weakMap = new WeakMap();
weakMap.set(obj, 'metadata');

// Checking existence
console.log(weakMap.has(obj)); // true

// Removing strong reference
obj = null;

// The object can now be garbage collected
console.log(weakMap.has(obj)); // false

βœ… Key Points

  • Keys must be objects

  • Weak reference allows automatic garbage collection

  • Not iterable (no .keys() or .values())


πŸ”Ή WeakSet in JavaScript

A WeakSet is similar to Set, but only stores objects weakly.
They are useful for memory-sensitive applications.

Example:

let obj1 = { name: 'Vishal' };
let obj2 = { name: 'Sagar' };

const weakSet = new WeakSet();
weakSet.add(obj1);
weakSet.add(obj2);

console.log(weakSet.has(obj1)); // true

obj1 = null; // obj1 can be garbage collected automatically

βœ… Key Points

  • Stores objects only

  • Weakly referenced β†’ memory-efficient

  • Not iterable


πŸ’» Practice Questions Using Map & Set

  1. Contains Duplicate – Use Set to check duplicates

  2. Intersection of Two Arrays – Use Set for efficient lookup

  3. Distribute Candies – Use Set to count unique candies

  4. Longest Consecutive Sequence – Use Set for O(n) solution

  5. Happy Number – Track seen numbers using Set

  6. First Unique Character In A String – Use Map for counts

  7. Find Common Characters – Use Map for character frequency

  8. Sort Characters By Frequency – Use Map and Set

  9. Valid Sudoku – Use Set for row/column/subgrid validation

  10. Longest Substring Without Repeating Characters – Use Set for sliding window


πŸ“ Practice Question Solutions β€” Map & Set in JavaScript


1️⃣ Contains Duplicate

Check if an array contains duplicate values.

const containsDuplicate = (nums) => {
    const set = new Set(nums);
    return set.size !== nums.length;
}

console.log(containsDuplicate([1,2,3,1])); // true
console.log(containsDuplicate([1,2,3]));   // false

βœ… Time Complexity: O(n)
βœ… Space Complexity: O(n)


2️⃣ Intersection of Two Arrays

Return the intersection of two arrays (unique values).

const intersection = (nums1, nums2) => {
    const set1 = new Set(nums1);
    const result = new Set();

    for (const num of nums2) {
        if (set1.has(num)) result.add(num);
    }

    return [...result];
}

console.log(intersection([1,2,2,1], [2,2])); // [2]

βœ… Time Complexity: O(n + m)
βœ… Space Complexity: O(n)


3️⃣ Distribute Candies

Return the max number of unique candies.

const distributeCandies = (candies) => {
    const unique = new Set(candies);
    return Math.min(unique.size, candies.length / 2);
}

console.log(distributeCandies([1,1,2,2,3,3])); // 3

βœ… Time Complexity: O(n)
βœ… Space Complexity: O(n)


4️⃣ Longest Consecutive Sequence

Find the length of the longest consecutive elements sequence.

const longestConsecutive = (nums) => {
    const set = new Set(nums);
    let longest = 0;

    for (const num of set) {
        if (!set.has(num - 1)) {
            let current = num;
            let streak = 1;

            while (set.has(current + 1)) {
                current++;
                streak++;
            }

            longest = Math.max(longest, streak);
        }
    }

    return longest;
}

console.log(longestConsecutive([100,4,200,1,3,2])); // 4

βœ… Time Complexity: O(n)
βœ… Space Complexity: O(n)


5️⃣ Happy Number

Determine if a number eventually reaches 1 by repeatedly summing the squares of its digits.

const isHappy = (n) => {
    const seen = new Set();

    while (n !== 1 && !seen.has(n)) {
        seen.add(n);
        n = n.toString()
             .split('')
             .reduce((sum, d) => sum + Math.pow(Number(d), 2), 0);
    }

    return n === 1;
}

console.log(isHappy(19)); // true
console.log(isHappy(2));  // false

βœ… Time Complexity: O(log n) per iteration
βœ… Space Complexity: O(log n)


6️⃣ First Unique Character In A String

const firstUniqChar = (s) => {
    const map = new Map();

    for (const char of s) {
        map.set(char, (map.get(char) || 0) + 1);
    }

    for (let i = 0; i < s.length; i++) {
        if (map.get(s[i]) === 1) return i;
    }

    return -1;
}

console.log(firstUniqChar("leetcode")); // 0
console.log(firstUniqChar("loveleetcode")); // 2

βœ… Time Complexity: O(n)
βœ… Space Complexity: O(n)


7️⃣ Find Common Characters

const commonChars = (words) => {
    const result = [];
    let map = new Map();

    for (const char of words[0]) {
        map.set(char, (map.get(char) || 0) + 1);
    }

    for (let i = 1; i < words.length; i++) {
        const temp = new Map();
        for (const char of words[i]) {
            if (map.has(char) && map.get(char) > 0) {
                temp.set(char, (temp.get(char) || 0) + 1);
                map.set(char, map.get(char) - 1);
            }
        }
        map = temp;
    }

    for (const [char, count] of map) {
        for (let i = 0; i < count; i++) result.push(char);
    }

    return result;
}

console.log(commonChars(["bella","label","roller"])); // ["e","l","l"]

βœ… Time Complexity: O(n * m) (n = number of words, m = max word length)
βœ… Space Complexity: O(26)


8️⃣ Sort Characters By Frequency

const frequencySort = (s) => {
    const map = new Map();
    for (const char of s) {
        map.set(char, (map.get(char) || 0) + 1);
    }

    return [...s].sort((a, b) => map.get(b) - map.get(a)).join('');
}

console.log(frequencySort("tree")); // "eert" or "eetr"

βœ… Time Complexity: O(n log n)
βœ… Space Complexity: O(n)


9️⃣ Valid Sudoku

const isValidSudoku = (board) => {
    const rows = [], cols = [], boxes = [];

    for (let i = 0; i < 9; i++) {
        rows.push(new Set());
        cols.push(new Set());
        boxes.push(new Set());
    }

    for (let r = 0; r < 9; r++) {
        for (let c = 0; c < 9; c++) {
            const val = board[r][c];
            if (val === ".") continue;

            const boxIndex = Math.floor(r / 3) * 3 + Math.floor(c / 3);

            if (rows[r].has(val) || cols[c].has(val) || boxes[boxIndex].has(val)) return false;

            rows[r].add(val);
            cols[c].add(val);
            boxes[boxIndex].add(val);
        }
    }

    return true;
}

βœ… Time Complexity: O(1) (board size fixed 9x9)
βœ… Space Complexity: O(1)


πŸ”Ÿ Longest Substring Without Repeating Characters

const lengthOfLongestSubstring = (s) => {
    const set = new Set();
    let left = 0, maxLen = 0;

    for (let right = 0; right < s.length; right++) {
        while (set.has(s[right])) {
            set.delete(s[left]);
            left++;
        }
        set.add(s[right]);
        maxLen = Math.max(maxLen, right - left + 1);
    }

    return maxLen;
}

console.log(lengthOfLongestSubstring("abcabcbb")); // 3

βœ… Time Complexity: O(n)
βœ… Space Complexity: O(min(n, charset size))

🎯 Final Thoughts

  • Use Set for unique values

  • Use Map for key-value pairs with any key type

  • Use WeakMap/WeakSet for memory-sensitive objects

  • Perfect for algorithmic challenges and real-world applications


🎯 Summary

  • Set / WeakSet β†’ Unique elements, memory efficient

  • Map / WeakMap β†’ Key-value pairs, any key type (Weak β†’ garbage collected)

  • These structures are great for solving common algorithm problems efficiently