输入如下:[ { gameId: id_0, groups: [1] }, { gameId: id_1, groups: [2] }, { gameId: id_2, groups: [1, 2] }, { gameId: id_3, groups: [3] }]我希望我的 reduce 产生一系列对象,例如:[ { group: 1, data: [ id_0, id_2 // gameId ] }, { group: 2, data: [ id_1, id_2 ] }, { group: 3, data: [ id_3 ] }]我能够通过使用数组索引来部分解决这个问题。我目前拥有的代码是:groupByArr = parameter => data => data.reduce((acc, curr) => { curr[parameter].forEach(key => { if (acc[key]) { acc[key].push(curr) } else { acc[key] = [curr] } }) return acc}, [])它生成一个数组数组,其中主数组索引是组 ID:[ empty, 1: [ id_0, id_2 ], 2: [ id_1, id_2 ], 3: [ id_3 ]]
3 回答
慕桂英4014372
TA贡献1871条经验 获得超13个赞
你应该试试这个。在分组场景中使用reduce是 JavaScript 为我们提供的最好的东西
let arr = [
{
gameId: "id_0",
groups: [1]
},
{
gameId: "id_1",
groups: [2]
},
{
gameId: "id_2",
groups: [1, 2]
},
{
gameId: "id_3",
groups: [3]
}
];
const grouped = arr.reduce((acc, current) => {
for(let x of current.groups){
if(!acc[x]) {
acc[x] = {group: x, data:[current.gameId]}
} else {
acc[x].data.push(current.gameId)
}
}
return acc
},{});
console.log(Object.values(grouped))
添加回答
举报
0/150
提交
取消