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
The code for this will be −
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
The output in the console will be −
[ 9, 90, 26, 4, 14 ]