Reduce an array to the sum of every nth element - 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.

Let's write the code for this function ?

Example

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 

99

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

1+5+5+12+65+2+9 = 99

How It Works

The function works by iterating through the array and checking if each index is a multiple of the given number n. When i % num === 0, it means the index is a multiple of n, so we add that element to our running sum.

Alternative Approach Using Filter and Reduce

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

const nthSumFunctional = (arr, num) => {
    return arr
        .filter((_, index) => index % num === 0)
        .reduce((sum, current) => sum + current, 0);
};

console.log(nthSumFunctional(arr, num));
console.log("Elements at indices 0, 3, 6, 9, 12:", arr.filter((_, i) => i % num === 0));
83
Elements at indices 0, 3, 6, 9, 12: [ 1, 3, 12, 3, 9 ]

Comparison

Method Readability Performance Memory Usage
For Loop Good Better Lower
Filter + Reduce Better Good Higher

Conclusion

Both approaches effectively sum elements at indices that are multiples of n. The for loop approach is more memory-efficient, while the functional approach using filter and reduce is more readable and follows functional programming principles.

Updated on: 2026-03-15T23:18:59+05:30

311 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements