跳至主要內容

Javascript Group By

Zhao Bin笔记frontendcode-snippetsjsjavascript

Javascript Group By

Object 数组分组

下面的代码是用来按数组对象的指定属性来排序。

代码

export const groupBy = (arr: any[], key: string): any[] | null => {
  if (arr) {
    const grouped = arr.reduce((group: any, obj: any) => {
      const data = obj[key]
      group[data] = group[data] ?? []
      group[data].push(obj)
      return group
    }, {})

    return grouped
  }

  return null
}

示例

对象数组分组