Adding two values at a time from an array - JavaScript

Let's say, we are required to write a JavaScript function that takes in an array of Numbers and returns a new array with elements as sum of two consecutive elements from the original array.

For example, if the input array is ?

const arr = [3, 6, 3, 87, 3, 23, 2, 2, 6, 8];

Then the output should be ?

const output = [9, 90, 26, 4, 14];

Example

Following is the code ?

const arr = [3, 6, 3, 87, 3, 23, 2, 2, 6, 8];
const twiceSum = arr => {
    const res = [];
    for(let i = 0; i < arr.length; i += 2){
        res.push(arr[i] + (arr[i+1] || 0));
    };
    return res;
};
console.log(twiceSum(arr));

Output

This will produce the following output in console ?

[ 9, 90, 26, 4, 14 ]

How It Works

The function iterates through the array with a step of 2 (i += 2), taking pairs of elements. For each iteration:

  • arr[i] - gets the first element of the pair
  • arr[i+1] || 0 - gets the second element, or 0 if it doesn't exist (for odd-length arrays)
  • The sum is pushed to the result array

Alternative Method Using reduce()

Here's another approach using the reduce() method:

const arr = [3, 6, 3, 87, 3, 23, 2, 2, 6, 8];

const twiceSumReduce = arr => {
    return arr.reduce((result, current, index) => {
        if (index % 2 === 0) {
            result.push(current + (arr[index + 1] || 0));
        }
        return result;
    }, []);
};

console.log(twiceSumReduce(arr));
[ 9, 90, 26, 4, 14 ]

Handling Edge Cases

Let's test with arrays of different lengths:

// Odd length array
const oddArr = [1, 2, 3, 4, 5];
console.log("Odd length:", twiceSum(oddArr));

// Empty array
const emptyArr = [];
console.log("Empty array:", twiceSum(emptyArr));

// Single element
const singleArr = [10];
console.log("Single element:", twiceSum(singleArr));
Odd length: [ 3, 7, 5 ]
Empty array: []
Single element: [ 10 ]

Conclusion

This approach efficiently sums consecutive pairs in an array using a for loop with step increment. The || operator handles odd-length arrays gracefully by adding 0 when no pair exists.

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

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements