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

感情迁移 提交于 2019-12-20 04:23:08

问题


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) => y) // -> 3, all good

// 2
[1,2,3,4,5].filter(x => x<=3).reduce((x, y) => 0) // -> 0, still good

// 3
[1,2,3,4,5].filter(x => x==3).reduce((x, y) => 0) // -> 3, hello?

In other words: how come the reduction on the array of one element ignores the map to 0 operation? This would ultimately be used on an array of objects, as in .reduce((x,y) => y.attr) which also returns y instead of y.attr for single element arrays.


回答1:


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



来源:https://stackoverflow.com/questions/37143814/array-prototype-reduce-on-arrays-of-one-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!