I have an array of objects, let's say [{x:2, y:3}, {x:5, y:4}]
and i call reduce((c, n) => c.y + n.y);
on it. It obviouslly returns 7
.
However, if the array contains a single object, let's say [{x:2, y:4}]
the same reduce call will return the object itself {x:2, y:4}
.
Is this normal behaviour? Am I obliged to check if the result is an object and not an number afterwards?
Yes, this is the normal behaviour of reduce
when you don't pass an initial value for the accumulator (which you always should). Your code doesn't work as expected on any arrays other than those with two objects.
Go for
arr.reduce((acc, el) => acc + el.y, 0)
It is intended behaviour, when you don't provide an initial value (second argument to reduce
). From MDN:
If the array is empty and no
initialValue
was provided,TypeError
would be thrown. If the array has only one element (regardless of position) and noinitialValue
was provided, or ifinitialValue
is provided but the array is empty, the solo value would be returned without callingcallback
.
It comes with the following advise:
It is usually safer to provide an initial value because there are three possible outputs without
initialValue
.
So write:
reduce((c, n) => c.y + n.y, { y: 0 });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With