Thrice sum of elements of array - JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject 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 sum of three consecutive elements from the original array.

For example, if the input array is −

const arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Then the output should be −

const output = [3, 12, 21, 9];

Example

Following is the code −

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

Output

This will produce the following output in console −

[ 3, 12, 21, 9 ]
raja
Published on 30-Sep-2020 17:23:52
Advertisements