Skip to main content

indexBy

indexBy() function

Given f that generates a key, turns a list of objects into an object indexing the objects by the given key. Note that if multiple objects generate the same value for the indexing key only the last value will be included in the generated object.

Signature:

declare function indexBy<A extends Key>(f: (a: A) => A, iterable: Iterable<A>): {
[K in A]: K;
};

Example

const given = [
{ category: "clothes", desc: "good" },
{ category: "pants", desc: "bad" },
{ category: "shoes", desc: "not bad" },
];

indexBy(a => a.category, given);
// {
// clothes: { category: "clothes", desc: "good" },
// pants: { category: "pants", desc: "bad" },
// shoes: { category: "shoes", desc: "not bad" },
// };

Try It

Open Source Code