reduce() 方法对数组中的每个元素执行一个给定的reducer函数(升序执行),并将其结果累计为单个返回值
reducer 函数接收4个参数:
accumulator (acc) (累计器) : 累计回调的返回值; 它是上一次调用回调时返回的累积值,或着显示提供的 initialValue
currentValue (cur) (当前值)
currentIndex (idx) (当前索引)
sourceArray (src) (源数组)
reducer 函数的返回值分配给累计器,该返回值在数组的每个迭代中被记住,并最后成为最终的单个结果值
语法:arr.reduce(callback(accumulator, currentValue[, index[, array]])[, initialValue])
- 按属性对object分类
const studentList = [
{ name: 'Zhangsan', age: 21 },
{ name: 'Lisi', age: 20 },
{ name: 'HanMeimei', age: 20 },
{ name: 'XiaoMing', age: 21 }
]
/**
* objectArray 目标对象数组
* property 对象属性
* obj 自定义对象
* acc 累计器累计回调的返回值,它是上一次调用回调时返回的累积值
*/
function groupByProp(objectArray, property) {
return objectArray.reduce((acc, obj) => {
let key = obj[property]
if (!acc[key]) {
acc[key] = []
}
// acc最终是要返回的,因为所有处理的数据都是放到acc中的
acc[key].push(obj)
return acc
}, {}) // {} 表示是initialValue, 则 acc就是这个{}
}
let groupedPeople = groupByProp(studentList, 'age')
/**
{20: Array(2), 21: Array(2)}
20: Array(2)
0: {name: "Lisi", age: 20}
1: {name: "HanMeimei", age: 20}
length: 2
__proto__: Array(0)
21: Array(2)
0: {name: "Zhangsan", age: 21}
1: {name: "XiaoMing", age: 21}
length: 2
__proto__: Array(0)
__proto__: Object
*/
- 累加求和
const numArr = [0, 1, 2, 3, 4, 5]
const total = numArr.reduce(function(acc, currVal) {
return acc + currentIndex
// 这里没有定义初始值,则initialValue是以第一次回调函数执行后返回的值作为acc
})
// 或直接使用箭头函数
const total = numArr.reduce((acc, currVal) => acc + currVal)
3.将二维数组转化为一维
const arr = [
[{name: 'zhang', age: 20}],
[{name: 'lisi', age: 21}],
[{name: 'wangwu', age: 22}]
]
const flatArr = arr.reduce((acc, currVal) => {
return acc.concat(currVal)
}, []) // initialValue为[]
/**
(3) [{…}, {…}, {…}]
0: {name: "zhang", age: 20}
1: {name: "lis", age: 21}
2: {name: "wangwu", age: 22}
length: 3
__proto__: Array(0)
*/
- 计算数组中元素出现的次数
const nums = [1, 2, 1, 3, 4, 2, 4, 5, 6]
const countNums = nums.reduce((allNums, num) => {
if (num in allNums) {
allNums[num]++
} else {
allNums[num] = 1
}
}, {}) // 这里initialValue是一个{}, 则表示acc就是这个值,这里allNums就是这个{}