Add two consecutive elements from the original array and display the result in a new array with JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

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 arrayOne = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];

Then the output should be −

const newArrayOne = [1, 5, 9, 13, 17]

Let's write the code for this function −

Example

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

Output

The output in the console will be −

[ 1, 5, 9, 13, 17 ]
raja
Published on 31-Aug-2020 13:48:47
Advertisements