Skip to content

toMapByKey

Builds a Map from an iterable of items, keyed by a derived key. When two items derive the same key, the later item wins (last-write-wins, matching Map.prototype.set semantics).

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/map';
// or, from the all-in-one package (same code, one install):
import { toMapByKey } from 'helpers4/map';
toMapByKey<T, K>(items: Iterable<T>, fn: function): Map<K, T>
ParameterTypeDescription
itemsIterable<T>The items to index
fnfunctionFunction deriving the key for each item

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

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

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

When two items derive the same key, the later one overwrites the earlier one.

toMapByKey([{ id: 'a', n: 1 }, { id: 'a', n: 2 }], item => item.id).get('a')
// => { id: 'a', n: 2 }

View source on GitHub