reduce

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.

reduce

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循环快

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容