JavaScript Array Reduce Doesn't Like Objects

bob.ts - Jun 25 '20 - - Dev Community

Recently, I was attempting to sum the values of an array that contained objects, like so ...

const pie = [
  { data: 10, color: "#ECD078" },
  { data: 20, color: "#D95B43" },
  { data: 10, color: "#C02942" },
  { data: 10, color: "#542437" },
  { data: 10, color: "#53777A" }
];
Enter fullscreen mode Exit fullscreen mode

I simply wanted the sum of the data keys. I tried ...

const pieTotal = pie.reduce((a, b) => a.data + b.data, 0);
Enter fullscreen mode Exit fullscreen mode

... and kept getting NaN as a result. When I got some add consoles.log values I decided to dig into reduce and quickly found Array.prototype.reduce(), which showed the (a, b) were not actually two values as I had assumed, but (accumulator, currentValue).

That's what I get for assuming from a Stack Overflow example.

Here's the working reduce code ...

const pieTotal =  pie.reduce((a, b) => a + b.data, 0);
Enter fullscreen mode Exit fullscreen mode

Just a reminder to myself to never assume functionality and to regularly check the documentation.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .