Javascript - 使用 reduce 方法的分组函数
Javascript - Grouping function with reduce method
谁能一步一步解释一下下面的函数?我在 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')
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
。然后回调完成一个条目的工作 returns acc
,这意味着它在下一次传递时再次接收它。
谁能一步一步解释一下下面的函数?我在 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')
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
。然后回调完成一个条目的工作 returns acc
,这意味着它在下一次传递时再次接收它。