Implementing partial sum over an array using JavaScript


Problem

We are required to write a JavaScript function that takes in an array of numbers. Our function should construct and return a new array in which each corresponding element is the sum of all the elements right to it (including it) in the input array.

Example

Following is the code −

 Live Demo

const arr = [5, 6, 1, 3, 8, 11];
const partialSum = (arr = []) => {
   let sum = arr.reduce((acc, val) => acc + val);
   const res = [];
   let x = 0;
   if(arr.length === 0){
      return [0];
   }
   for(let i = 0; i <= arr.length; i += 1) {
      res.push(sum);
      x = arr[i];
      sum -= x;
   };
   return res;
};
console.log(partialSum(arr));

Output

[ 34, 29, 23, 22, 19, 11, 0 ]

Updated on: 17-Apr-2021

295 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements