Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
Selected Reading
Finding sum of every nth element of array in JavaScript
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.
Example
The code for this will be −
const arr = [5, 3, 5, 6, 12, 5, 65, 3, 2];
const num = 3;
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
The output in the console −
76
Advertisements
