The webpage works fine as long as I don't pass an initial value, but in that case it just gives me the TypeError because when there's only the last element (as expected). Which is why I am trying to pass 0 as the initial value to the reduce function (line 4 of below snippet). But as soon as I do that, it just breaks the entire page with an error code 6.
What I'm trying to achieve: I'm adding the sum of all the elements of the array, then pushing that sum to another array, removing the first element and repeating the process. When there are no elements left, I want to return 0 from the reduce() function which is why I'm trying to pass an initial value (0).
function partsSums(ls) {
let sumArr = [];
while (ls.length >= 0) {
sumArr.push(ls.reduce((acc, cur) => acc + cur, 0));
ls.shift();
}
return sumArr;
}
partsSums([0, 1, 3, 6, 10]);
The output I'm looking for is: [20, 20, 19, 16, 10, 0]
you can do that: