Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript reduce returns object on Array of objects

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?

like image 765
Jo Colina Avatar asked Feb 21 '17 21:02

Jo Colina


2 Answers

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)
like image 123
Bergi Avatar answered Sep 29 '22 16:09

Bergi


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 no initialValue was provided, or if initialValue is provided but the array is empty, the solo value would be returned without calling callback.

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 });
like image 31
trincot Avatar answered Sep 29 '22 16:09

trincot