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 ]

Updated on: 18-Sep-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements