I am trying to implement an efficient group by alogrithm from Most efficient method to groupby on an array of objects and trying to put the types. But I get the error:
T[keyof T] cannot be used to index {}
Here is my attempt
static groupBy<T>(xs:T[], key: keyof T) {
return xs.reduce((rv, x)=> {
(rv[x[key]] = rv[x[key]] || []).push(x);
return rv;
}, {});
};
rv: any
rv will be any .
class A {
static groupBy<T>(xs: T[], key: keyof T) {
return xs.reduce((rv: any, x) => {
(rv[x[key]] = rv[x[key]] || []).push(x);
return rv;
}, {});
}
}
How to use it:
interface Person {
name: string;
age: number;
salary: number;
}
const data: Person[] = [
{name:"deepak", age: 30, salary: 2000},
{name:"deepak1", age: 32, salary: 1000},
{name:"deepak", age: 29, salary: 3000}
]
class A {
static groupBy<T>(xs: T[], key: keyof T) {
return xs.reduce((rv: any, x) => {
(rv[x[key]] = rv[x[key]] || []).push(x);
return rv;
}, {});
}
}
console.log(A.groupBy(data, "name"))
Defination from Lodash:
groupBy(
predicate?: Lodash.ListIterator<T, boolean> | Lodash.DictionaryIterator<T, boolean> | string,
thisArg?: any,
): Lodash.Dictionary<T[]>;
groupBy<R extends {}>(predicate?: R): Lodash.Dictionary<T[]>;
Sync group return an object and object cant have any other element as key other than string|number. Else you can follow more genric solution.
interface Any<T> {
[key: string]: T[];
}
interface SMap<T> {
[key: string]: T;
}
class A {
static groupBy<T extends SMap<string>>(xs: T[], key: keyof T) {
return xs.reduce((rv: Any<T>, x) => {
if (!rv[x[key]]) {
rv[x[key]] = [];
}
rv[x[key]].push(x);
return rv;
}, {});
}
}
if you don't want to use any
, you need properly define types to tell that reducer can combine data.
function groupBy<T extends {[LK in K]: keyof any}, K extends keyof T>(xs:T[], key: K) {
return xs.reduce<{[LK2 in T[K]]?: Array<T>}>((rv, x) => {
(rv[x[key]] = rv[x[key]] || [])?.push(x);
return rv;
}, {});
};
const result = groupBy([{ test: 'key' }], 'test');
result.key?.length; // 1
T is an object where type of passed key is something that can be used as a key (for rv).
for reducer - it starts with an empty object - we need to says that result will be an object where value of the key is an array of entities from the xs {[LK2 in T[K]]?: Array<T>}
Not as short as the original. However, it does not use "any" or "as" casting. It also supports any data type for the group key, hence, unknown.
export function groupBy<T>(xs: T[], key: keyof T): Map<unknown, T[]> {
return xs.reduce((rv: Map<unknown, T[]>, entity: T) => {
const value = entity[key];
if (rv.has(value)) {
rv.get(value)?.push(entity)
} else {
rv.set(value, [entity]);
}
return rv;
}, new Map());
};
example of usage:
const badgesByTypes = groupBy(currentState.badges, 'type');
for (const [key, values] of badgesByTypes.entries()) {
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.