arr.reduce(callback[accumulator, currentValue, currentIndex, array], initialValue)
接受一个数组作为输入值并返回一个值。
接受一个回调函数,回调函数参数包括一个累计器(数组每一段的累加值,它会像雪球一样增长),当前值,和索引。
accumulator
The accumulator accumulates callback's return values. It is the accumulated value previously returned in the last invocation of the callback—or initialValue, if it was supplied (see below).
Your reducer function's returned value is assigned to the accumulator, whose value is remembered across each iteration throughout the array, and ultimately becomes the final, single resulting value.
reducer回调函数接受四个参数:accumulator,currentValue,currentIndex,sourceArray
如果提供了initialValue,则累加器将等于initialValue,currentValue将等于数组中的第一个元素
如果没有提供initialValue,则累加器将等于数组中的第一个元素,currentValue将等于数组中的第二个元素。
reduce包含两个参数:回调函数,传给total的初始值
//求数组的各项值相加的和:
arr.reduce((total, item)=> { // total为之前的计算结果,item为数组的各项值
return total + item;
}, 0);
Counting instances of values in an object
let names=['Alice','Bob','Tiff','Bruce','Alice']
let countedNames=names.reduce(function(allNames,name){
if(nameinallNames){allNames[name]++}
else{allNames[name]=1}
returnallNames}
,{})
// countedNames is:
// { 'Alice': 2, 'Bob': 1, 'Tiff': 1, 'Bruce': 1 }
Grouping objects by a property
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')
// groupedPeople is:
{
20: [
{ name: 'Max', age: 20 },
{ name: 'Jane', age: 20 }
],
21: [
{ name: 'Alice', age: 21 }
]
}
Function composition enabling piping
// Building-blocks to use for composition
const double=x=>x+x
const triple=x=>3*x
const quadruple=x=>4*x
// Function composition enabling pipe functionality
const pipe=(...functions)=>input=>functions.reduce((acc,fn)=>fn(acc),input)
// Composed functions for multiplication of specific values
const multiply6=pipe(double,triple)
const multiply9=pipe(triple,triple)
const multiply16=pipe(quadruple,quadruple)
const multiply24=pipe(double,triple,quadruple)
// Usage
multiply6(6)// 36
multiply9(9)// 81
multiply16(16)// 256
multiply24(10)// 240
实现一下reduce
为什么reduce函数求和比for循环快