Everything runs smoothly on the webpage unless I provide an initial value, causing a TypeError due to only one remaining element (as expected). In an attempt to fix this, I decided to pass 0 as the initial value for the reduce function (line 4 in the code snippet below). Unfortunately, this action results in the entire page breaking with error code 6.
The goal I'm aiming for: My objective is to sum all elements within an array, append that sum to another array, eliminate the first element, and repeat the process until no elements remain. At that point, I want the reduce() function to return 0, hence my need to supply an initial value of 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 desired output I am seeking: [20, 20, 19, 16, 10, 0]