How to make a list of partial sums using forEach JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

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.

So, the output should look like −

const output = [1, 2, 7, 9, 5, 11, 21];

Let’s write the function partialSum(). The full code for this function will be −

Example

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.

Output

So, the output for this code will be −

[
   1, 2, 7, 9,
   5, 11, 21
]
raja
Updated on 19-Aug-2020 07:04:11

Advertisements