# Reverse sum array JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

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. Therefore, let's write the code for this function −

## 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 < first.length && j >= 0;
i++, j--, k++){
sumArray[k] = first[i] + second[j];
};
while(i < first.length){
sumArray[k] = first[i];
k++;
i++;
};
while(j >= 0){
sumArray[k] = second[j];
k++;
j--;
};
return sumArray;
};
console.log(reverseSum(first, second));

## Output

The output in the console will be −

[
35, 37, 30, 58, 41,
13, 12, 21, 4, 2
]

Let’s see how the output is showing these numbers. For example, 35 above, is the sum of first element of first array and last element of second array as first element, i.e. −

 23 (First element of first array)
+12 (Last element of second array)
------
35
Published on 28-Aug-2020 14:09:34