Javascript Reduce Throwing Error For More Than Two Items
Solution 1:
Actually you need only to return the accumulator + the new value.
You want to begin with 0
i guess so you need to add 0
as second parameter
const arr =
[
{ someProp: [{ amount: 10 }]},
{ someProp: [{ amount: 12 }]},
{ someProp: [{ amount: 12 }]},
];
const sum = arr.reduce((acc, item) => item.someProp[0].amount + acc, 0);
console.log(sum);
If you want it more spicy here with destructuring
const arr =
[
{ someProp: [{ amount: 10 }]},
{ someProp: [{ amount: 12 }]},
{ someProp: [{ amount: 12 }]},
];
const sum = arr.reduce((acc, { someProp: [{ amount }] }) => amount + acc, 0);
console.log(sum);
Solution 2:
Following @Pointy answer, this is how you can get it working with any number of elements:
const sum = arr.reduce((prev, curr) => prev + curr.someProp[0].amount, 0);
prev
is always the previously returned element, so you can safely use it as a number (and since you're just summing it, you can use 0
as default, so the first time reduce
is invoked the value of prev
will be 0)
Solution 3:
You're returning a number. The value of prev
is always the prior return value from the callback, not the previous element. Thus on the third iteration you're trying to use that number as if it were an object reference.
Add a second parameter (0) to the .reduce()
call, and change the function to treat prev
as the running total (a simple number):
const sum = arr.reduce((prev, curr) => prev + curr.someProp[0].amount, 0);
It works as-is when there are two elements because without that second parameter, the first iteration will see element 0 as prev
and element 1 as curr
. That behavior works fine when you've got an array of numbers and you just want to perform a computation between them, but in this case you need that initial value explicitly there as the second argument.
Post a Comment for "Javascript Reduce Throwing Error For More Than Two Items"