分组求和
function GroupBy(datas,keys,callBack) {
const list = datas || [];
const groups = [];
list.forEach(v => {
const key = {};
const data = {};
keys.forEach(k => {
key[k] = v[k];
});
let group = groups.find(v => {
return v._key === JSON.stringify(key);
});
if (!group) {
group = {
_key:JSON.stringify(key),
key: key,
};
groups.push(group);
}
if(callBack){
group.data = callBack(group.data,v);
group.total=group.total||0;
group.total++;
}else {
group.data=group.data||[];
group.data.push(v);
}
});
return groups;
}
测试函数
window.onload=function () {
const data = [
{key:1,key2:1,v:123},
{key:1,key2:1,v:55},
{key:2,key2:1,v:85},
{key:1,key2:2,v:15},
{key:2,key2:1,v:99}
];
var d = GroupBy(data,['key','key2'],(d,v)=> {
d = d||0;
return d+=v.v;
});
console.log(d);
var a = GroupBy(data,['key','key2']);
console.log(a);
};
效果图
网友评论