Reduce an array to the sum of every nth element - JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in an array of numbers and returns the cumulative sum of every number present at the index that is a multiple of n from the array.

Let’s write the code for this function −

const arr = [1, 4, 5, 3, 5, 6, 12, 5, 65, 3, 2, 65, 9];
const num = 2;
const nthSum = (arr, num) => {
   let sum = 0;
   for(let i = 0; i < arr.length; i++){
      if(i % num !== 0){
         continue;
      };
      sum += arr[i];
   };
   return sum;
};
console.log(nthSum(arr, num));

Output

Following is the output in the console −

99

Above, we added every 2nd element beginning with index 0 i.e.

1+5+5+12+65+2+9 = 99
raja
Published on 14-Sep-2020 17:57:20
Advertisements