Reduce() in depth

后端 未结 3 686
再見小時候
再見小時候 2021-01-22 01:31

In ES5, the new array method reduce(). I am wondering if someone can explain more in depth.

3条回答
  •  梦谈多话
    2021-01-22 02:06

    The reduce() method is an iterator it loops through all the elements in an array and does something with the results. The reduce() function accepts a callback function. This the function that actually executes whatever you want it to do for every iteration. This function is a special function

    the first parameter this function takes is previous value the second parameter this function takes is current value and two other parameters (let just make this simple)

    lets consider we have an array

    arr=[1,2,3,4,5,6]
    

    using reduce by creating a function called sum

    function sum(previousvalue,currentvalue,index,ar){
    return previousvalue+currentvalue
    }
    

    and finally we place a reference of this function in the reduce method

    arr.reduce(sum)
    

    executing this we get 21

    What really is this special function doing? let's consider

    [1,2,3,4,5,6]

    function sum says

    Wrong! "let me take the current element value in this array " == 1
    
    
    Right! # the function starts at the second element in the array so the previous element is the 1st element
    
     "let me add the current element value to the prev. element value in this array and remember this value " == 1+2
    
    
    "okay I am moving on to the next value"==3
    
    "okay..I will add the next value to the previous summed up value"==3+3
    "now I will save this value and do the same thing again until I loop to the end"
    

    But wait what is the practical use of this, I can write this easily without using the reduce function?

    It is like a generator function (like in some languages such as python)..it doesn't remember values except the previous call value and the current value...(some memory efficiency advantage)

    example finding moving averages

       function sum(previousvalue,currentvalue,index,ar){
        return (previousvalue+currentvalue/2)
        }
    

    the function above is the revision of a the same old funciton i was using

    -It takes the first two element find the average and save the value -It takes the next element add it the average and find another average and the cycle goes on

提交回复
热议问题