1

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.

3
  • there is only one element Commented May 10, 2016 at 16:10
  • 1
    part of the spec: "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." developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented May 10, 2016 at 16:11
  • This obviously had to lead to some RTFM answer of sorts. Many thanks for calling it a day for me! Commented May 10, 2016 at 16:17

1 Answer 1

14

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.