Keyed collections: Map for arbitrary keys, Set for unique values.

Introduction

Map and Set hold keyed or unique values, keep insertion order, and are iterable.

  • Map (developer.mozilla.org)
  • Set (developer.mozilla.org)

Map

const map = new Map()
map.set('a', 1).set('b', 2)   // set() chains, returns map
map.get('a')                  // → 1
map.has('a')                  // → true
map.size                      // → 2 (property, not a method)
map.delete('a')               // → true
map.clear()                   // removes everything
const key = {}
const map = new Map([['a', 1], [key, 2]])
map.get(key)        // → 2 (identity, not value)
map.get({})         // → undefined (different object)
map.set(NaN, 'x')
map.get(NaN)        // → 'x' (SameValueZero)
const map = new Map([['a', 1], ['b', 2]])
for (const [key, value] of map) console.log(key, value)
[...map.keys()]     // → ['a', 'b']
[...map.values()]   // → [1, 2]
[...map.entries()]  // → [['a', 1], ['b', 2]]
[...map]            // same as entries
map.forEach((value, key) => ...)

Plain objects coerce keys to strings; Map keeps the original key type. Keys compare with SameValueZero, so NaN equals NaN.

See: Map, Map.set(), Map.forEach() (developer.mozilla.org)

Set

const set = new Set([1, 2, 2, 3])
set.size             // → 3 (duplicates dropped)
set.has(2)           // → true
set.add(4)           // returns the set
set.delete(2)        // → true
set.clear()
[...new Set([1, 1, 2])]      // → [1, 2] (dedupe)
const set = new Set(['a', 'b'])
for (const value of set) console.log(value)
[...set]                     // → ['a', 'b']
[...set.keys()]              // same as values

Sets store unique values; adding an existing value is a no-op. Iteration follows insertion order.

See: Set, Set.add() (developer.mozilla.org)

Conversions

Object.fromEntries(map)       // map to plain object
new Map(Object.entries(obj))  // plain object to a Map
[...map]                      // → array of [key, value]
Array.from(set)               // set to array
[...set]                      // → array

Object.fromEntries() stringifies keys, and Object.entries() reads only own enumerable string keys.

See: Object.fromEntries(), Object.entries() (developer.mozilla.org)

WeakMap and WeakSet

const cache = new WeakMap()
cache.set(element, { data: 1 })
cache.get(element)   // → { data: 1 }
cache.has(element)   // → true
cache.delete(element)
const seen = new WeakSet()
seen.add(element)
seen.has(element)    // → true
seen.delete(element)

Keys must be objects or non-registered symbols, entries are not enumerable, and they are garbage collected with the key. There is no .size or .clear().

See: WeakMap, WeakSet (developer.mozilla.org)

0 Comments for this cheatsheet. Write yours!