Adding two values at a time from an array - JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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 ]
raja
Published on 18-Sep-2020 10:00:25
Advertisements