Cumulative sum of elements in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

Suppose, we have an array of numbers like this −

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

We are required to write a JavaScript function that takes in one such array and returns a new array with corresponding elements of the array being the sum of all the elements upto that point from the original array.

Therefore, for the above array, the output should be −

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

Example

The code for this will be −

const arr = [1, 2, 3, 4, 5, 6];
const findCumulativeSum = arr => {
   const creds = arr.reduce((acc, val) => {
      let { sum, res } = acc;
      sum += val;
      res.push(sum);
      return { sum, res };
   }, {
      sum: 0,
      res: []
   });
   return creds.res;
};
console.log(findCumulativeSum(arr));

Output

The output in the console −

[ 1, 3, 6, 10, 15, 21 ]
raja
Published on 12-Oct-2020 11:11:49
Advertisements