Js对数据实现分组GroupBy特性

一个用于分组的代码片段(有注释)

let list = [{
     "name": "John",
     "Average": 15,
     "High": 10,
     "DtmStamp": 1358226000000
},
{
     "name": "Jane",
     "Average": 16,
     "High": 92,
     "DtmStamp": 1358226000000
},
{
     "name": "Jane",
     "Average": 17,
     "High": 45,
     "DtmStamp": 1358226000000
},
{
     "name": "John",
     "Average": 18,
     "High": 87,
     "DtmStamp": 1358226000000
},
{
     "name": "Jane",
     "Average": 15,
     "High": 10,
     "DtmStamp": 1358226060000
},
{
     "name": "John",
     "Average": 16,
     "High": 87,
     "DtmStamp": 1358226060000
},
{
     "name": "John",
     "Average": 17,
     "High": 45,
     "DtmStamp": 1358226060000
},
{
     "name": "Jane",
     "Average": 18,
     "High": 92,
     "DtmStamp": 1358226060000
}
];

function GroupBy(array, fn) {
debugger;
const groups = {};
array.forEach(function (item) {
     const group = JSON.stringify(fn(item));
     //这里利用对象的key值唯一性的,创建数组
     groups[group] = groups[group] || [];
     groups[group].push(item);
});
//最后再利用map循环处理分组出来
return Object.keys(groups).map(function (group) {
     return groups[group];
});
}

//这里如果想要按照name进行分组即如下:
const results = GroupBy(list, function (item) {
return [item.name];
});

console.log(results)

你可能感兴趣的:(Js对数据实现分组GroupBy特性)