Js对数据实现分组GroupBy特性
我根据查找的资料,写了一个通用的
GroupbyKey(array,key){
let groups = {};
let strResult =[];
for(let i=0; i<array.length ;i++){
const group =JSON.stringify(array[i][key]);
//这里利用对象的key值唯一性的,创建数组
groups[group] = groups[group] || [];
groups[group].push(array[i]);
}
Object.keys(groups).map(u =>{
groups[u].map(p =>{
strResult.push(p);
})
});
return strResult;
}
array是如下类型
list : [
{
"name": "John",
"Average": 15,
"High": 10,
"DtmStamp": 1358226000000
}
,
{
"name": "Jane",
"Average": 16,
"High": 92,
"DtmStamp": 1358226000000
}
,
{
"name": "Jane",
"Average": 18,
"High": 92,
"DtmStamp": 1358226060000
}
]
调用方法如下,以哪个键值分组就传那个键值属性名
const results = this.GroupbyKey(list,"name");
择善人而交,择善书而读,择善言而听,择善行而从。