
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
Thrice sum of elements of array - JavaScript
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 ]
- Related Articles
- Absolute sum of array elements - JavaScript
- Sum of distinct elements of an array - JavaScript
- Sum of distinct elements of an array in JavaScript
- Maximum sum of n consecutive elements of array in JavaScript
- Finding sum of alternative elements of the array in JavaScript
- Sum of all the non-repeating elements of an array JavaScript
- Alternating sum of elements of a two-dimensional array using JavaScript
- Consecutive elements sum array in JavaScript
- Finding desired sum of elements in an array in JavaScript
- Pair of (adjacent) elements of an array whose sum is lowest JavaScript
- Adjacent elements of array whose sum is closest to 0 - JavaScript
- Cumulative sum of elements in JavaScript
- Sum all similar elements in one array - JavaScript
- Sum identical elements within one array in JavaScript
- How to find the sum of all elements of a given array in JavaScript?

Advertisements