Array.reduce()的用法
reduce() 方法对数组中的每个元素执行一个由您提供的reducer函数(升序执行),将其结果汇总为单个返回值。(定义)
arr.reduce(callback(accumulator, currentValue[, index[, array]])[, initialValue])
reducer函数接收4个参数:
Accumulator (acc) (累计器)如果传入了initialValue,Accumulator的初始值就是initialValue,没传入就是数组的第一个值
Current Value (cur) (当前值)
Current Index (idx) (当前索引)如果传入了initialValue,索引从0开始,没传入从1开始如果传入了initialValue,索引从0开始,没传入从1开始
Source Array (src) (源数组)
initialValue 指定的初始值,初始值可以是数字,数组,对象
您的reducer函数的返回值分配给累计器,该返回值在数组的每个迭代中被记住,并最后成为最终的单个结果值。
实用场景
1、数组里值求和
let sum=[0,1,2,3].reduce(function(accumulator, currentValue){
return accumulator+currentValue;
},0);// 和为 6
// accumulator会把上一次循环返回的结果存起来,带到下一次循环中,使用reduce方法可以很容易的计算数组累加
// 对象数组求和
const arr = [{
count: 10,
width: 1,
height: 2},
{count: 20,
width: 2,
height: 4}, {
count: 30,
width: 3,
height: 6}, {
count: 40,
width: 4,
height: 8}]
// 合计count
const obj = arr. reduce((acc, cur) => {
return acc + cur.count
}, 0)
console.log(obj) // 100// 合计count, width, height
const obj2 = arr. reduce((acc, cur) => {
for(let key in cur) {
if(!acc[key]) {
acc[key] = 0 }
acc[key] += cur[key]
}
return acc
}, {})
console.log(obj2) // {count: 100, width: 10, height: 20}
2、统计数组元素出现的次数
// 普通数组统计let arr = ['李雷', 'Jerry', '张三', '李雷', '李雷', '张三', 'Jerry', '李雷', 'Jack', 'Jerry']
const sum = arr. reduce((acc, cur) => {
if(!acc[cur]) {
acc[cur] = 0 }
acc[cur]++return acc
}, {})
console.log(sum) // {李雷: 4, Jerry: 3, 张三: 2, Jack: 1}
// 对象数组统计
let arr1 = [{
hobby: 'basketball'}, {
hobby: 'badminton'}, {
hobby: 'basketball'}, {
hobby: 'swimming'}, {
hobby: 'basketball'}, {
hobby: 'swimming'}, {
hobby: 'volleyball'}]
const sum2 = arr1. reduce((acc, cur) => {
if(!acc[cur.hobby]) {
acc[cur.hobby] = 0 }
acc[cur.hobby]++return acc
}, {})
console.log(sum2) // {basketball: 3, badminton: 1, swimming: 2, volleyball: 1}
3.二维数组转化为一维数组
let arr =[1,2,3,4,[1],[2,3,4,4],0]
let res = arr. reduce(function(acc, cur){
return acc.concat(cur)
},[])
4、数组去重
// 普通数组去重
let arr = [1, 3, 3, 2, 4, 4, 3, 5, 2, 5, 6]
let newArr = arr. reduce((acc, cur) => {
if(!acc.includes(cur)) {
acc.push(cur)
}
return acc
}, [])
console.log(newArr) // (6) [1, 3, 2, 4, 5, 6]// 对象数组去重, 对象数组去重需指定以哪个对象属性来去重
let arr1 = [{
name: '李雷',
age: 18}, {
name: 'Jerry',
age: 18}, {
name: 'Jerry',
age: 20}, {
name: '李雷',
age: 20}, {
name: 'jack',
age: 22}, {
name: '张三',
age: 22}]
function unique (arr, key) {
let obj = {}
let newArr1 = arr. reduce((acc, cur) => {
if(!obj[cur[key]]) {
obj[cur[key]] = cur[key]
acc.push(cur)
}
return acc
}, [])
return newArr1
}
// 姓名去重console.log(unique(arr1, 'name'))
// 0: {name: "李雷", age: 18}
// 1: {name: "Jerry", age: 18}
// 2: {name: "jack", age: 22}
// 3: {name: "张三", age: 22}
// age去重console.log(unique(arr1, 'age'))
// 0: {name: "李雷", age: 18}
// 1: {name: "Jerry", age: 20}
// 2: {name: "jack", age: 22}