I have this array:
const arr = [
{ someProp: [{ amount: 10 }]},
{ someProp: [{ amount: 12 }]},
];
and then this reduce fn:
con
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)
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);
This is an alternative solution... Using Array.filter()
.
const arr = [{
someProp: [{
amount: 10
}]
},
{
someProp: [{
amount: 12
}]
},
{
someProp: [{
amount: -231
}]
},
{
someProp: [{
amount: 21265
}]
},
{
someProp: [{
amount: 1239
}]
},
{
someProp: [{
amount: -6
}]
},
];
const sum = arr.filter((val, index) => {
if (index > 0) {
arr[index].someProp[0].amount = parseInt(val.someProp[0].amount) + parseInt(arr[index - 1].someProp[0].amount);
}
return index == arr.length - 1;
})[0].someProp[0].amount;
console.log(sum);
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.