首页 > 解决方案 > Javascript - 使用reduce方法的分组函数

问题描述

有人可以逐步解释以下功能吗?当 reduce 的主体开始时,我失去了它:

let people = [
  { name: 'Alice', age: 21 },
  { name: 'Max', age: 20 },
  { name: 'Jane', age: 20 }
];

function groupBy(objectArray, property) {
  return objectArray.reduce(function (acc, obj) {
    let key = obj[property]
    if (!acc[key]) {
      acc[key] = []
    }
    acc[key].push(obj)
    return acc
  }, {})
}

let groupedPeople = groupBy(people, 'age')

标签: javascriptarrayssortinggroupingreduce

解决方案


reduce使该功能看起来比实际更复杂。(reduce被过度使用,并且几乎总是错误的工具与简单的循环。)这是没有不必要的相同功能reduce,并有解释:

function groupBy(objectArray, property) {
  // The object we'll return with properties for the groups
  let result = {}
  // Loop through the array
  for (const obj of objectArray) {
    // Get the key value
    let key = obj[property]
    // If the result doesn't have an entry for that yet, create one
    if (!result[key]) {
      result[key] = []
    }
    // Add this entry to that entry
    result[key].push(obj)
  }
  // Return the grouped result
  return result
}

reduce版本只是传递result(as acc):使用reduce初始值({}您在调用结束附近看到的reduce)和第一个条目调用回调,回调接收为accand obj。然后回调完成一个条目的工作并返回acc,这意味着它会在下一次传递中再次接收它。


推荐阅读