Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 ]
Advertisements