Reduce基本用法
定义:数组中的每个元素按序执行 reducer 函数,每一次运行 reducer 会将先前元素的计算结果作为参数传入,最后将其结果汇总为单个返回值
语法:array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
参数:回调函数(callback)、初始值(initialValue)
参数:
total:累加器的结果(必选)
currentvalue:当前累加器的值(必选)
currentIndex:当前累加器的索引(可选)
arr:当前元素的所属数组(可选)
举例
数组累加
let arr = [1, 2, 3, 4, 5, 6]
function accumFunc(arr) {
let newVal = arr.reduce((total, curValue) => {
return total + curValue
}, 0)
return newVal
}
console.log(accumFunc(arr))
数组去重
let arr = [1,2,3,'x','y','z',1,2,3,'x','y','z']
function removeDuplicates(arr){
let newArr = arr.reduce((total, curValue) => {
if (!total.includes(curValue)) {
total.push(curValue)
}
return total
}, [])
return newArr
}
console.log(removeDuplicates(arr))
数组扁平化
let arr = [[1,2,3],['x','y','z'],['大','帅','哥']]
function flatAry(arr) {
let newArr = arr.reduce((total, curValue) => {
return total.concat(curValue)
}, [])
return newArr
}
console.log(removeDuplicates(arr))
颠倒数组
let arr = ['我', '要', '颠', '倒']
function reverseAry(arr) {
let newAry = arr.reduceRight((total, curValue) => {
total.push(curValue)
return total
}, [])
return newAry
}
console.log(reverseAry(arr))