javascript reduce () method example

    Reduce is a merging process in the big data framework mapreduce. All data is merged according to certain rules, the scope is reduced step by step, and finally merged into a largest collection or object.

     In javascript, the reduce method is a method of an array. It receives a function and an initial value as parameters. The calling format is as follows:

    array.reduce(function(prev,cur){},initialValue)

    Function parameters can be freely defined according to different usage scenarios. Generally, the simplest application is for summation. Examples are as follows:

const sum = (a,b)=>a+b 
const $sum = [1,2,3,4,5].reduce(sum,0)
console.log($sum)

    This is the simplest example. The sum function name sum only requires us to pass in as a parameter. The final result is 15.

    

    The reduce function can also merge objects as follows:

     

    The above two examples can be said to be the most intuitive application of the reduce function. In another case, we can nest multiple functions and use the result of the first function as the parameter of the second function, and so on, which can constitute a complex calculation.

      

    This process calculates 2 * 2 * 10 * ^ 2, and the final result is 1600. If you do not use reduce to do the calculation, then this calculation method needs to be implemented to achieve power (f10 (f2 (2))). If there are more functions and the nesting method is less readable, the reduce function is used to achieve simple recursion Called to enhance code readability.

 

Published 529 original articles · praised 287 · 1.47 million views

Guess you like

Origin blog.csdn.net/feinifi/article/details/103981863