Finding sum of alternative elements of the array in JavaScript

We are required to write a JavaScript function that takes in an array of Numbers as the only argument. The function should calculate and return the sum of alternative elements of the array.

For example ?

If the input array is ?

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

Then the output should be ?

1 + 3 + 5 + 7 = 16

Method 1: Using for Loop with Index Check

This approach uses a for loop and checks if the index is even to sum alternative elements:

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

const alternativeSum = (arr = []) => {
    let sum = 0;
    for(let i = 0; i < arr.length; i++){
        const el = arr[i];
        if(i % 2 !== 0){
            continue;
        };
        sum += el;
    };
    return sum;
};

console.log(alternativeSum(arr));
16

Method 2: Using for Loop with Step Increment

A more direct approach that increments by 2 to skip alternative elements:

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

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

console.log(alternativeSum(arr));
16

Method 3: Using filter() and reduce()

A functional programming approach using filter and reduce methods:

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

const alternativeSum = (arr = []) => {
    return arr
        .filter((el, index) => index % 2 === 0)
        .reduce((sum, el) => sum + el, 0);
};

console.log(alternativeSum(arr));
16

Testing with Different Arrays

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

// Test with different arrays
console.log(alternativeSum([10, 20, 30, 40]));     // 10 + 30 = 40
console.log(alternativeSum([5]));                  // 5
console.log(alternativeSum([]));                   // 0
console.log(alternativeSum([2, 4, 6, 8, 10]));     // 2 + 6 + 10 = 18
40
5
0
18

Comparison

Method Time Complexity Space Complexity Readability
for Loop with Index Check O(n) O(1) Good
for Loop with Step Increment O(n/2) O(1) Best
filter() and reduce() O(n) O(n/2) Good (Functional)

Conclusion

The step increment approach (Method 2) is most efficient as it only iterates through alternate elements. Use filter/reduce for functional programming style, though it requires extra memory for the filtered array.

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

997 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements