Skip to content

Documentation / @andrew_l/toolkit / keyBy

Function: keyBy() ​

Maps each element of an array based on a provided key.

Each key holds one element; when several elements share a key, the last one wins.

Example ​

ts
const data = [
    { id: 1, name: 'group 1' },
    { id: 2, name: 'group 2' },
    { id: 1, name: 'group 2' }
];

const result = keyBy(data, 'id');
console.log([...result]);
// [
//    [1, { id: 1, name: 'group 2' }],
//    [2, { id: 2, name: 'group 2' }],
// ]

Replaces ​

new Map(list.map(x => [x.id, x])) — keyBy(list, 'id') builds the same Map (the last item wins for a repeated key) without the intermediate array of pairs; the key can also be a function.

Detect ​

new Map\(\s*[\w.]+\.map\(\s*\(?\w+\)?\s*=>\s*\[\s*\w+(\.\w+|\[[^\]]+\])\s*,\s*\w+\s*\]\s*,?\s*\)\s*,?\s*\)\s*[^.\s]

Replaces ​

Object.fromEntries(list.map(x => [x.id, x])) — keyBy(list, 'id', true) returns the same plain object (the last item wins) in one pass.

Detect ​

Object\.fromEntries\(\s*[\w.]+\.map\(\s*\(?\w+\)?\s*=>\s*\[\s*\w+(\.\w+|\[[^\]]+\])\s*,\s*\w+\s*\]\s*\)\s*\)

Call Signature ​

keyBy<T, K>(array, keyBy, objectMode?): Map<IsPropertyKey<T, K, unknown>, T>

Type Parameters ​

T ​

T

K ​

K extends string | number | symbol

Parameters ​

array ​

readonly T[]

keyBy ​

K

objectMode? ​

false

Returns ​

Map<IsPropertyKey<T, K, unknown>, T>

Call Signature ​

keyBy<T, K>(array, keyBy, objectMode?): Map<IsPropertyKey<T, K, unknown>, T>

Type Parameters ​

T ​

T

K ​

K extends PropertyKey

Parameters ​

array ​

readonly T[]

keyBy ​

K

objectMode? ​

false

Returns ​

Map<IsPropertyKey<T, K, unknown>, T>

Call Signature ​

keyBy<T, K>(array, keyBy, objectMode?): Map<K, T>

Type Parameters ​

T ​

T

K ​

K

Parameters ​

array ​

readonly T[]

keyBy ​

(item) => K

objectMode? ​

false

Returns ​

Map<K, T>

Call Signature ​

keyBy<T, K>(array, keyBy, objectMode): Record<ToPropertyKey<T[K]>, T>

Type Parameters ​

T ​

T

K ​

K extends string | number | symbol

Parameters ​

array ​

readonly T[]

keyBy ​

K

objectMode ​

true

Returns ​

Record<ToPropertyKey<T[K]>, T>

Call Signature ​

keyBy<T, K>(array, keyBy, objectMode): Record<ToPropertyKey<IsPropertyKey<T, K, unknown>>, T>

Type Parameters ​

T ​

T

K ​

K extends PropertyKey

Parameters ​

array ​

readonly T[]

keyBy ​

K

objectMode ​

true

Returns ​

Record<ToPropertyKey<IsPropertyKey<T, K, unknown>>, T>

Call Signature ​

keyBy<T, K>(array, keyBy, objectMode): Record<ToPropertyKey<K>, T>

Type Parameters ​

T ​

T

K ​

K

Parameters ​

array ​

readonly T[]

keyBy ​

(item) => K

objectMode ​

true

Returns ​

Record<ToPropertyKey<K>, T>

Released under the MIT License.