Skip to content

Instantly share code, notes, and snippets.

@dir01
Created May 14, 2019 09:31
Show Gist options
  • Save dir01/e65453d192fc2e1a37f6bbe113cdb8d3 to your computer and use it in GitHub Desktop.
Save dir01/e65453d192fc2e1a37f6bbe113cdb8d3 to your computer and use it in GitHub Desktop.
const groupBy = <T extends { [k in K]: string }, K extends string>(
arr: T[],
attr: K,
) => {
return arr.reduce<{ [k in T[K]]?: T[] }>((result, item) => {
const k = item[attr];
if (result[k] === undefined) {
result[k] = [];
}
(result[k] as T[]).push(item);
return result;
}, {});
};
test("groupBy", () => {
const data = [
{ type: "foo", id: 1 },
{ type: "foo", id: 2 },
{ type: "bar", id: 3 },
];
expect(groupBy(data, "type")).toEqual({
foo: [data[0], data[1]],
bar: [data[2]],
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment