shfshanyue / Daily-Question

互联网大厂内推及大厂面经整理,并且每天一道面试题推送。每天五分钟,半年大厂中
https://q.shanyue.tech
4.92k stars 508 forks source link

【Q679】实现一个函数 groupBy #698

Open shfshanyue opened 3 years ago

shfshanyue commented 3 years ago

类似 lodash.groupBy

groupBy([
  { id: 1, name: '山月', sex: 'male' },
  { id: 2, name: '张三', sex: 'female' },
  { id: 3, name: '李四', sex: 'female' }
], x => x.sex)
shfshanyue commented 3 years ago
function groupBy (collection, by) {
  return collection.reduce((acc, x) => {
    if (acc[by(x)]) { acc[by(x)].push(x)}
    else { acc[by(x)] = [x] }
    return acc 
  }, {})
}
heretic-G commented 3 years ago

function groupBy (data, filter) {
    const map = {}
    data.forEach(curr => {
        const key = filter(curr)
        if (!map[key]) map[key] = []
        map[key].push(curr)
    })
    return map
}
JoeWrights commented 2 years ago
function groupBy(arr = [], callback) {
  const obj = {}
  const keys = arr.map(callback)
  keys.forEach(key => {
    obj[key] = []
  })

  arr.forEach(ele => {
    obj[callback(ele)].push(ele)
  })

  return obj
}