javascript - 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')
解决方案
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
)和第一个条目调用回调,回调接收为acc
and obj
。然后回调完成一个条目的工作并返回acc
,这意味着它会在下一次传递中再次接收它。
推荐阅读
- ios - iOS 15 上的 CoreLocation didUpdateHeading.headingAccuracy 精度低
- c++ - 将 static_casted 方法作为模板参数传递
- c# - 为什么 XYFocus 对 xbox uwp 应用程序不正确?
- javascript - svg 作为光标 url 值没有被应用
- cakephp - cakephp 如何按范围数据查找分组?
- serverless - 无服务器使用 ENV 或资源参考
- javascript - 如何在间隔上显示/隐藏元素
- php - 多个 Laravel Eloquent 关系未显示来自所有关系的数据
- powershell - 在 Outlook 中使用 powershell 中的类别创建约会
- google-analytics - 每次加载都会建立缓存