//Example 1:
var primaryColors = [
{ color: 'red' },
{ color: 'blue' },
{ color: 'yellow' },
];
var answer = primaryColors.reduce((x,y) => x.push(y.color) , []);
//x.push is not a function
//Example 2:
var ints = [1,2,3];
var sum = ints.reduce((sum, number) => sum + number, 0);
//sum = 6
As shown above, Example 1 will be throwing exception TypeError: x.push is not a function
. In order to make it works, we can add a pair of curly braces and returning value as below.
var answer = primaryColors.reduce((x,y) => { x.push(y.color); return x;}, []);
Now I don't really understand the need of return
. Why Example 2 can sum without using the keyword return
while Example 1 needed a return keyword in order to work?
Why does Example 1 need a return keyword in order to work?
The problem is that x.push()
returns the new length of the array, so that's what your callback to .reduce()
returns. But .reduce()
will take the return value from your callback and pass it as the next value for x
in the next iteration of the loop. So you need to return x
.
The way you're doing it, the second time your callback is called, x
will be 1
and 1.push()
is an error.
If you don't understand why you need return x
, then study the doc for .reduce()
more thoroughly. x
is the accumulator and the value of x
in the next iteration of your callback will be whatever you return from the prior one.
Why Example 2 can sum without using the keyword return
Because your example 2, returns sum + number
which is what you want passed as sum for the next iteration of the loop. So, it's returning the right thing.
FYI, your first loop is perhaps more easily done with .map()
:
//Example 1:
var primaryColors = [
{ color: 'red' },
{ color: 'blue' },
{ color: 'yellow' },
];
var answer = primaryColors.map(item => item.color);
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments