Array.prototype.reduce() on arrays of one element

前端 未结 1 1602
遥遥无期
遥遥无期 2021-01-24 08:02

In following reduction + map operations, no. 3 is puzzling me. Can anyone please explain why

// 1
[1,2,3,4,5].filter(x => x==3).reduce((x, y) =&g         


        
相关标签:
1条回答
  • 2021-01-24 08:35

    The filtered array contains only one element so reduce will return that value.

    Read the docs :

    If the array has only one element (regardless of position) and no initialValue was provided, or if initialValue is provided but the array is empty, the solo value would be returned without calling callback.

    For more : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

    0 讨论(0)
提交回复
热议问题