猿问

根据数组类型键对对象数组进行分组

输入如下:


[

  {

    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

  ]

]


DIEA
浏览 138回答 3
3回答

慕桂英4014372

你应该试试这个。在分组场景中使用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))
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答