typedash
Version:
modern, type-safe collection of utility functions
41 lines (39 loc) • 1.06 kB
JavaScript
//#region src/functions/keyBy/keyBy.ts
/**
* Creates an object composed of keys generated from the results of running each element of `array` through `keyGetter`.
* The corresponding value of each key is the last element responsible for generating the key.
* @param array The array to iterate over.
* @param keyGetter The function used to extract the key from each element.
* @returns An object with the keys mapped to the elements.
* @example
* ```ts
* keyBy(
* [
* { id: 'a', value: 1 },
* { id: 'b', value: 2 },
* { id: 'c', value: 3 },
* ],
* (item) => item.id
* )
* // {
* // a: { id: 'a', value: 1 },
* // b: { id: 'b', value: 2 },
* // c: { id: 'c', value: 3 }
* // }
* ```
*/
function keyBy(array, keyGetter) {
return array.reduce((draftObject, currentItem) => {
const key = keyGetter(currentItem);
draftObject[key] = currentItem;
return draftObject;
}, {});
}
//#endregion
Object.defineProperty(exports, 'keyBy', {
enumerable: true,
get: function () {
return keyBy;
}
});
//# sourceMappingURL=keyBy-Bx8eEPsQ.cjs.map