亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

根據數組類型鍵對對象數組進行分組

根據數組類型鍵對對象數組進行分組

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))


查看完整回答
反對 回復 2021-10-21
  • 3 回答
  • 0 關注
  • 156 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號