DIEA
2021-10-21 16:53:14
輸入如下:[ { 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
提交
取消