Reverse sum array JavaScript

We are required to write a function, say reverseSum() that takes in two arrays of Numbers, let's say first and second and returns a new array that contains:

  • Sum of first element of first array and last element of second array as first element,

  • sum of second element of first array and second last element of second array, and so on.

When any of the array runs out of element before the other, we simply push all the remaining elements to the array.

Syntax

const reverseSum = (first, second) => {
    // Implementation logic
    return sumArray;
};

Example

const first = [23, 5, 7, 2, 34, 7, 8];
const second = [2, 4, 21, 4, 6, 7, 56, 23, 32, 12];

const reverseSum = (first, second) => {
    const sumArray = [];
    let i, j, k;
    
    for(i = 0, j = second.length - 1, k = 0; i = 0; i++, j--, k++){
        sumArray[k] = first[i] + second[j];
    };
    
    while(i = 0){
        sumArray[k] = second[j];
        k++;
        j--;
    };
    
    return sumArray;
};

console.log(reverseSum(first, second));
[
  35, 37, 30, 58, 41,
  13, 12, 21, 4, 2
]

How It Works

First Array: 23 5 7 ... Second Array: 12 32 23 ... 23 + 12 = 35 5 + 32 = 37 Result Array: 35 37 30 ... Pattern: first[i] + second[length-1-i]

The algorithm pairs elements from the start of the first array with elements from the end of the second array. When one array is exhausted, remaining elements from the other array are added directly.

Step-by-Step Breakdown

Let's trace through how 35 is calculated:

23 (First element of first array)
+12 (Last element of second array)
------
35

The function uses three pointers: i for the first array (forward), j for the second array (backward), and k for the result array position.

Conclusion

The reverseSum function efficiently combines two arrays by pairing elements from opposite directions. This approach creates a unique pattern where array elements are summed in a cross-directional manner.

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

516 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements