相当于C#LINQ GroupBy的Javascript
这是以下问题的后续问题: 我们使用的是Angular 2+类型脚本: 我有一个对象数组。数组中的每个对象都包含一个名为“StudentType”的属性 我需要运行一个C#LINQ风格的查询,提取数组中StudentType的列表以及具有该特定类型的数组成员的数量 虽然我可以做一个老派的循环并做到这一点,但我想知道是否有更好的方法来做到这一点,比如C#LINQ GroupBy提供的方法相当于C#LINQ GroupBy的Javascript,javascript,angular,typescript,Javascript,Angular,Typescript,这是以下问题的后续问题: 我们使用的是Angular 2+类型脚本: 我有一个对象数组。数组中的每个对象都包含一个名为“StudentType”的属性 我需要运行一个C#LINQ风格的查询,提取数组中StudentType的列表以及具有该特定类型的数组成员的数量 虽然我可以做一个老派的循环并做到这一点,但我想知道是否有更好的方法来做到这一点,比如C#LINQ GroupBy提供的方法 因为我们使用的是Angular 2,所以项目负责人不允许使用JQuery 我刚刚编写了一些studentTyp
因为我们使用的是Angular 2,所以项目负责人不允许使用JQuery 我刚刚编写了一些studentType值用于测试,但您可以使用它来迭代输入数组的每个元素,并添加或操作累加器对象的属性
让arr=[{
学生类型:“新生”
},
{
学生类型:“高级”
},
{
学生类型:“大二”
},
{
学生类型:“新生”
},
{
学生类型:“初级”
},
{
学生类型:“高级”
},
{
学生类型:“大二”
},
{
学生类型:“新生”
},
{
学生类型:“大二”
},
{
学生类型:“新生”
}
];
让结果=arr.reduce((上一个,当前)=>{
isNaN(上一个[当前学生类型])?上一个[当前学生类型]=1:上一个[当前学生类型]+;
返回上一个;
}, {});
控制台日志(结果)代码>我在TypeScript中创建了一个groupBy函数
export interface Group {
key: any;
items: any[];
}
export interface GroupBy {
keys: string[];
thenby?: GroupBy;
}
export const groupBy = (array: any[], grouping: GroupBy): Group[] => {
const keys = grouping.keys;
const groups = array.reduce((groups, item) => {
const group = groups.find(g => keys.every(key => item[key] === g.key[key]));
const data = Object.getOwnPropertyNames(item)
.filter(prop => !keys.find(key => key === prop))
.reduce((o, key) => ({ ...o, [key]: item[key] }), {});
return group
? groups.map(g => (g === group ? { ...g, items: [...g.items, data] } : g))
: [
...groups,
{
key: keys.reduce((o, key) => ({ ...o, [key]: item[key] }), {}),
items: [data]
}
];
}, []);
return grouping.thenby ? groups.map(g => ({ ...g, items: groupBy(g.items, grouping.thenby) })) : groups;
};
我在StackBlitz上做了一个演示
您可以从实现所有C#LINQ方法并保留其语法的manipula
包中进行尝试。这里有两个选项:
如果你被允许携带Lodash,它就具有你想要的功能。Ramda也一样:谢谢Stephen和Matt,loadlash或Ramda中的哪一个更适合使用TypeScript?如果在这种情况下,您将prev
参数重命名为acculator
,acc
,result
,count
或诸如此类的内容,可能会对读者有所帮助。编辑以包含该函数。
function GroupBy1(arr, key) {
var group = {};
arr.forEach(val => group[val[key]] = (group[val[key]] || 0) + 1);
return group;
}
function GroupBy2(arr, key) {
return arr.reduce((group, val) => {
group[val[key]] = (group[val[key]] || 0) + 1;
return count;
}, {});
}
var arr = [
{ studentType: 'freshman' },
{ studentType: 'senior' },
{ studentType: 'freshman' },
{ studentType: 'junior' },
{ studentType: 'sophmore' },
{ studentType: 'freshman' },
{ studentType: 'freshman' },
{ studentType: 'junior' },
{ studentType: 'senior' },
{ studentType: 'senior' },
{ studentType: 'freshman' },
{ studentType: 'sophmore' },
{ studentType: 'freshman' },
{ studentType: 'sophmore' },
{ studentType: 'senior' }
];
console.log(GroupBy1(arr, 'studentType'));
console.log(GroupBy2(arr, 'studentType'));