reduce() 方法接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值。
语法:array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
reduce() 可以作为一个高阶函数,用于函数的 compose。
注意: reduce() 对于空数组是不会执行回调函数的。
reduce() 的几个强大用法:
1.两两相加可以用来求和
var total = [ 2, 3, 4 ].reduce(( pre, next ) => {
return pre + next
}, 0);
console.log(total) // 9
2.二维数组转为一维数组
var array = [[1, 2], [3, 4], [5, 6]].reduce(( pre, next ) => {
return pre.concat(next)
}, []);
console.log(array) // [1, 2, 3, 4, 5, 6]
3.计算数组中每个元素出现的次数
- 方法一
let names = ['tom', 'jim', 'jack', 'tom', 'jack'];
const countNames = names.reduce((allNames, name) => {
if (name in allNames) {
allNames[name] ++;
} else {
allNames[name] = 1;
}
return allNames;
}, {});
console.log(countNames) // { tom: 2, jim: 1, jack: 2 }
- 方法二
const arraySum = (arr, val) => arr.reduce((acc, cur) => {
return cur == val ? acc + 1 : acc + 0
}, 0);
let arr = [ 0, 1, 3, 0, 2, 0, 2, 3 ]
console.log(arraySum(arr, 0)) // 数组arr中 0 元素出现的次数为3
4.数组去重(先排序然后再把对比前后不同的就push)
let arr = [1, 2, 1, 2, 3, 5, 4, 5, 3, 4, 4, 4, 4];
let result = arr.sort().reduce((init, current) => {
if (init.length === 0 || init[init.length - 1] !== current) {
init.push(current);
}
return init;
}, []);
console.log(result); //[1,2,3,4,5]
5.利用map构建新数据
var name = [
'sam\tblender\t200\t1 ',
'sam\tpot\t130\t5 ',
'nacy\tconaver\t20\t3 ',
'amy\tpot\t130\t2 ',
'amy\tblender\t4\t2 '
]
var output =
name.map((item)=>{item.trim().split('\t')})
.reduce((customers,line)=>{
customers[line[0]] = customers[line[0]] || [];
customers.push({
name: line[0],
property: line[1],
price:line[2],
quilty: line[3]
})
},{})