Convert Array of Numbers to Cumulative Sum Array in JavaScript
We have an array of numbers like this −
const arr = [1, 1, 5, 2, -4, 6, 10];
We are required to write a function that returns a new array, of the same size but with each element being the sum of all elements until that point.
Therefore, the output should look like −
const output = [1, 2, 7, 9, 5, 11, 21];
Therefore, let’s write the function partialSum(),
The full code for this function will be −
const arr = [1, 1, 5, 2, -4, 6, 10]; const partialSum = (arr) => { const output = []; arr.forEach((num, index) => { if(index === 0){ output[index] = num; }else{ output[index] = num + output[index - 1]; } }); return output; }; console.log(partialSum(arr));
Here, we iterated over the array and kept assigning the elements of output array a new value every time, the value being the sum of current number and its predecessor.
The output of the code in the console will be −
[ 1, 2, 7, 9, 5, 11, 21 ]
Advertisements