js对象数组分组
程序员文章站
2022-06-17 19:47:40
...
按照某个字段进行分组
let groupData = [
{name: "张三",project: "语文",score: "90"},
{name: "张三",project: "数学",score: "88"},
{name: "张三",project: "英语",score: "86"},
{name: "张三",project: "物理",score: "96"},
{name: "李四",project: "语文",score: "92"},
{name: "李四",project: "数学",score: "86"}
];
function groupByName(groupData) {
let result = groupData.reduce((prevValue, currentValue) => {
let index = -1;
prevValue.some((item, i) => {
if (item.name == currentValue.name) {
index = i;
return true;
}
})
if (index > -1) {
prevValue[index].projectAndScore.push({
project: currentValue.project,
score: currentValue.score
})
} else {
prevValue.push({
name: currentValue.name,
projectAndScore: [{
project: currentValue.project,
score: currentValue.score
}]
})
}
return prevValue;
}, []);
console.log(result);
return result;
}
groupByName(groupData);
分组结果如下:
上一篇: LeetCode二叉树简单题汇总
下一篇: 二维数组中的查找