Created
April 11, 2023 14:51
-
-
Save dually8/5260f182863ce36a9a8e65a597ed332d to your computer and use it in GitHub Desktop.
TypeScript GroupBy Replacement for Lodash
This file contains hidden or 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
import { groupBy } from './groupby.ts'; | |
describe('Array Utils Test', () => { | |
it('should test groupBy', () => { | |
const data = getGroupByData(); | |
const actual = groupBy(data, 'name'); | |
const expected = getGroupByExpected(); | |
expect(actual).toEqual(expected); | |
}) | |
}) | |
function getGroupByData() { | |
return [ | |
{ id: 1, name: 'ABC', }, | |
{ id: 2, name: 'XYZ', }, | |
{ id: 3, name: 'ABC', }, | |
] | |
} | |
function getGroupByExpected() { | |
return { | |
'ABC': [ | |
{ id: 1, name: 'ABC', }, | |
{ id: 3, name: 'ABC', }, | |
], | |
'XYZ': [ | |
{ id: 2, name: 'XYZ', }, | |
] | |
} | |
} |
This file contains hidden or 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
type GroupedByType<T> = { | |
[prop in keyof T]: Partial<T>[]; | |
}; | |
type AvailableKeys<T> = keyof T & string; | |
export function groupBy<T>(arr: T[], prop: AvailableKeys<T>): GroupedByType<T> { | |
const key: string = prop; // workaround for typescript shenanigans | |
return arr.reduce((result: GroupedByType<T>, obj: T) => { | |
(result[obj[key]] = result[obj[key]] || []).push(obj); | |
return result; | |
}, {} as GroupedByType<T>) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment