数组groupby

const students = [
  { name: 's1', age: 22, sex: 'female' },
  { name: 's2', age: 22, sex: 'male' },
  { name: 's3', age: 23, sex: 'female' },
  { name: 's4', age: 24, sex: 'male' },
  { name: 's6', age: 21, sex: 'male' },
  { name: 's5', age: 22, sex: 'female' },
  { name: 's7', age: 24, sex: 'female' }
]
arr = [1, 4, 2, 4, 5, 6, 5]
function groupBy(arr, generateKey) {
  if (typeof generateKey === 'string') {
    const attrKey = generateKey
    generateKey = (item) => item[attrKey]
  }
  const result = {}
  arr.forEach(item => {
    const key = generateKey(item)
    if (result.hasOwnProperty(key)) {
      result[key].push(item)
    } else {
      result[key] = [item]
    }
  })
  return result
}





console.log(groupBy(students, 'age'))
console.log(groupBy(students, item => item.sex))

 

posted @ 2024-07-18 16:35  howhy  阅读(5)  评论(0编辑  收藏  举报