Consecutive elements sum array in JavaScript


We are required to write a JavaScript function that takes in an array of Numbers and returns a new array with elements as the sum of two consecutive elements from the original array.

For example, if the input array is −

const arr1 = [1, 1, 2, 7, 4, 5, 6, 7, 8, 9];

Then the output should be −

const output = [2, 9, 9, 13, 17]

Example

The code for this will be −

const arr11 = [1, 1, 2, 7, 4, 5, 6, 7, 8, 9];
const consecutiveSum = arr => {
   const res = [];
   for(let i = 0; i < arr.length; i += 2){
      res.push(arr[i] + (arr[i+1] || 0));
   };
   return res;
};
console.log(conseutiveSum(arr1));

Output

The output in the console −

[ 2, 9, 9, 13, 17 ]

Updated on: 14-Oct-2020

383 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements