Skip to content

Instantly share code, notes, and snippets.

@dually8
Created April 11, 2023 14:51
Show Gist options
  • Save dually8/5260f182863ce36a9a8e65a597ed332d to your computer and use it in GitHub Desktop.
Save dually8/5260f182863ce36a9a8e65a597ed332d to your computer and use it in GitHub Desktop.
TypeScript GroupBy Replacement for Lodash
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', },
]
}
}
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