Skip to content

toMapByKey

Builds a Map from a Set, keyed by a derived key. When two values derive the same key, the later value (in iteration order) wins (last-write-wins, matching Map.prototype.set).

Named toMapByKey, not keyBy (lodash’s name for the same idea) — lodash’s _.keyBy returns a plain object, not a Map; the to<Type> prefix (matching toSorted/toReversed) makes the actual return type unambiguous.

Available since v3.0.3

import { toMapByKey } from '@helpers4/set';
// or, from the all-in-one package (same code, one install):
import { toMapByKey } from 'helpers4/set';
toMapByKey<T, K>(set: ReadonlySet<T>, fn: function): Map<K, T>
ParameterTypeDescription
setReadonlySet<T>The Set to index
fnfunctionFunction deriving the key for each value

Map<K, T> — A Map from derived key to value

Builds a Map keyed by a derived value, for O(1) lookup by that key.

toMapByKey(new Set([{ id: 'a' }, { id: 'b' }]), item => item.id)
// => Map(2) { 'a' => {...}, 'b' => {...} }

View source on GitHub