Accumulating array elements to form new array in JavaScript


Problem

We are required to write a JavaScript function that takes in an array of numbers, arr, as the first argument and a number, num, (num <= length of array) as the second argument

Our function should add up each contiguous subarray of length num of the array arr to form corresponding elements of new array and finally return that new array

For example, if the input to the function is −

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

Then the output should be−

const output = [3, 5, 7, 9, 11];

Output Explanation

Because 1 + 2 = 3, 2 + 3 = 5, and so on...

Example

Following is the code−

 Live Demo

const arr = [1, 2, 3, 4, 5, 6];
const num = 2;
const accumulateArray = (arr = [], num = 1) => {
   const res = [];
   let sum = 0, right = 0, left = 0;
   for(; right < num; right++){
      sum += arr[right];
   };
   res.push(sum);
   while(right < arr.length){
      sum -= arr[left];
      sum += arr[right];
      right++;
      left++;
      res.push(sum);
   };
   return res;
};
console.log(accumulateArray(arr, num));

Output

Following is the console output−

[3, 5, 7, 9, 11]

Updated on: 21-Apr-2021

116 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements