【问题标题】:Javascript - Grouping function with reduce methodJavascript - 使用reduce方法的分组函数
【发布时间】:2020-06-07 10:28:09
【问题描述】:

有人可以逐步解释以下功能吗?当 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')

【问题讨论】:

  • 如何将console.log 放在各处并跟踪代码的作用?
  • @grodzi - 或者,与其拿着console.log 手电筒在黑暗中跌跌撞撞,他还可以使用内置在他的IDE 或浏览器中的调试器打开灯
  • @grodzi 我已经做到了,但无法理解逻辑......
  • @T.J.克劳德,谢谢先生的回答。如果你想要它,你可以用你已经提供的解决方案来回答我的问题。

标签: javascript arrays sorting grouping reduce


【解决方案1】:

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(如acc):reduce 使用初始值调用回调({} 你在reduce 调用结束附近看到)和第一个条目,回调接收为accobj。然后回调完成一个条目的工作并返回acc,这意味着它会在下一次传递时再次接收它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-01-22
    • 2018-12-16
    • 2021-07-08
    • 2018-10-19
    • 2020-10-27
    • 1970-01-01
    • 2020-03-26
    相关资源
    最近更新 更多