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.

Understanding the Problem

When we say "every nth element", we mean elements at indices 0, n, 2n, 3n, and so on. For example, if n=3, we sum elements at indices 0, 3, 6, 9, etc.

Example

Let's find the sum of every 3rd element from an array:

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));
console.log("Elements at indices 0, 3, 6:", arr[0], arr[3], arr[6]);
console.log("Sum:", arr[0] + arr[3] + arr[6]);
76
Elements at indices 0, 3, 6: 5 6 65
Sum: 76

Alternative Approach Using Step Increment

Instead of checking every index, we can increment by n directly:

const nthSumOptimized = (arr, n) => {
    let sum = 0;
    for(let i = 0; i < arr.length; i += n){
        sum += arr[i];
    }
    return sum;
};

const arr = [5, 3, 5, 6, 12, 5, 65, 3, 2];
console.log(nthSumOptimized(arr, 3));
console.log(nthSumOptimized(arr, 2)); // Every 2nd element
76
82

Using Array Methods

A more functional approach using reduce():

const nthSumFunctional = (arr, n) => {
    return arr.reduce((sum, value, index) => {
        return index % n === 0 ? sum + value : sum;
    }, 0);
};

const arr = [5, 3, 5, 6, 12, 5, 65, 3, 2];
console.log(nthSumFunctional(arr, 3));
76

Comparison of Methods

Method Performance Readability Use Case
For loop with continue Good Clear General purpose
For loop with step increment Best Very clear When n is known and constant
Reduce method Good Functional style Functional programming preference

Conclusion

The step increment approach (i += n) is most efficient as it skips unnecessary iterations. Choose the method that best fits your coding style and performance requirements.

Updated on: 2026-03-15T23:19:00+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements