Main difference between map and reduce

后端 未结 6 1199
日久生厌
日久生厌 2020-12-12 12:38

I used both methods but I am quite confused regarding the usage of both methods.

Is anything that map can do but reduce can not and vice ve

6条回答
  •  悲&欢浪女
    2020-12-12 13:13

    The map() function returns a new array through passing a function over each element in the input array.

    This is different to reduce() which takes an array and a function in the same way, but the function takes 2 inputs - an accumulator and a current value.

    So reduce() could be used like map() if you always .concat onto the accumulator the next output from a function. However it is more commonly used to reduce the dimensions of an array so either taking a one dimensional and returning a single value or flattening a two dimensional array etc.

提交回复
热议问题