使用reduce方法的Javascript分组函数
有人能一步一步地解释以下功能吗?当reduce的主体开始时,我失去了它:使用reduce方法的Javascript分组函数,javascript,arrays,sorting,grouping,reduce,Javascript,Arrays,Sorting,Grouping,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 = ob
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')
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
调用末尾附近看到的{}
调用)和第一个条目调用回调函数,回调函数以acc
和obj
的形式接收。然后回调执行一个条目的工作并返回acc
,这意味着它在下一次传递时再次接收该条目。将console.log放在任何地方并跟踪代码的作用如何?@grodzi-或者,与其在黑暗中用console.log
火炬蹒跚而行,他可以使用IDE或浏览器中内置的调试器打开灯。@grodzi我已经完成了,但无法理解逻辑…@t.J.Crowder,谢谢您的回答。如果您需要,请用您已经提供的解决方案回答我的问题。