Skip to content

Instantly share code, notes, and snippets.

@Pogix3m
Last active December 3, 2020 06:05
Show Gist options
  • Save Pogix3m/c9e39c9829e6d810dfbdcceb5d4d640e to your computer and use it in GitHub Desktop.
Save Pogix3m/c9e39c9829e6d810dfbdcceb5d4d640e to your computer and use it in GitHub Desktop.
Group Array By Id in TypeScript
/* tslint:disable */
export {};
type TGroup<T> = {Id: any; Values: T[]};
declare global {
interface Array<T> {
groupBy(aKey: string): TGroup<T>[];
}
}
Array.prototype.groupBy = function<T>(aKey: string): TGroup<T>[]
{
const lReducer: any = (lPrevious: TGroup<T>[], lCurrentValue: T) =>
{
const lExisting: TGroup<T> | undefined
= lPrevious.find((aValue: TGroup<T>) => aValue.Id === lCurrentValue[aKey]);
if (lExisting)
{
lExisting.Values.push(lCurrentValue);
}
else
{
lPrevious.push(
{
Id: lCurrentValue[aKey],
Values: [lCurrentValue],
});
}
return lPrevious;
};
return this.reduce(lReducer, []);
};
@Pogix3m
Copy link
Author

Pogix3m commented May 13, 2020

require("./Array.extension.ts") --> Use correct path to load on your start up file

type T = {
    id: number;
    qty: number;
};
 const arr: T[] = [];
arr.push({id: 1, qty: 10});
arr.push({id: 1, qty: 100});
arr.push({id: 2, qty: 200});
arr.push({id: 2, qty: 2});
arr.groupBy("id"));

Result:

[
    {
        Id: 1,
        Values: [
            {
                id: 1,
                qty: 10
            },
            {
                id: 1,
                qty: 100
            }
        ]
    },
    {
        Id: 2,
        Values: [
            {
                id: 2,
                qty: 200
            },
            {
                id: 2,
                qty: 2
            }
        ]
    }
]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment