Cumulative sum at each index in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in an array of Numbers. The function constructs and return a new array that for a particular index, contains the sum of all the numbers up to that index.

For example −

If the input array is −

const arr = [1, 2, 3, 4, 5];

Then the output should be −

const output = [1, 3, 6, 10, 15];

We can use the Dynamic program to keep track of the sum in each iteration and just add the corresponding element to the sum to obtain the new element.

Example

Following is the code −

const arr = [1, 2, 3, 4, 5];
const cumulativeSum = arr => {
   let result = [arr[0]];
   for(let i = 1; i < arr.length; i++) {
      result.push(arr[i] + result[i-1]);
   }
   return result;
}
console.log(cumulativeSum(arr));

Output

Following is the output on console −

[ 1, 3, 6, 10, 15 ]
raja
Published on 10-Dec-2020 08:05:44
Advertisements