Created
May 14, 2019 09:31
-
-
Save dir01/e65453d192fc2e1a37f6bbe113cdb8d3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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