Skip to main content

keyBy

Maps each element of an array according to the given key-generating function.

Returns an object whose keys are generated by the iteratee function and whose values are the corresponding elements. If multiple elements produce the same key, the last element is used as the value.


Code​

🔗 View source code


Interface​

typescript
function keyBy<T, K extends PropertyKey>(
arr: T[] | readonly T[],
iteratee: (item: T, index: number, array: T[] | readonly T[]) => K
): Record<K, T>;

Usage​

typescript
import { keyBy } from '@modern-kit/utils';

const array = [
{ category: 'fruit', name: 'apple' },
{ category: 'fruit', name: 'banana' },
{ category: 'vegetable', name: 'carrot' },
];

keyBy(array, (item) => item.category);
// {
// fruit: { category: 'fruit', name: 'banana' },
// vegetable: { category: 'vegetable', name: 'carrot' }
// }

// Using the index parameter
keyBy(['a', 'b', 'c'], (_, index) => index);
// { 0: 'a', 1: 'b', 2: 'c' }