
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
Get average of every group of n elements in an array JavaScript
We are required to write a JavaScript function that takes in an array of Numbers as the first argument and a Number, say n, as the second argument. The function should return an array of averages of groups of n elements.
For example: If the inputs are −
const arr = [1, 2, 3, 4, 5, 6]; const n = 2;
Then the output should be −
const output = [1.5, 3.5, 5.5];
Example
const arr = [1, 2, 3, 4, 5, 6]; const n = 2; const groupAverage = (arr = [], n = 1) => { const res = []; for (let i = 0; i < arr.length;) { let sum = 0; for(let j = 0; j< n; j++){ sum += +arr[i++] || 0; }; res.push(sum / n); } return res } console.log(groupAverage(arr, n)) console.log(groupAverage(arr, 3))
Output
And the output in the console will be −
[ 1.5, 3.5, 5.5 ] [ 2, 5 ]
- Related Questions & Answers
- Calculating average of an array in JavaScript
- Find average of each array within an array JavaScript
- Realtime moving average of an array of numbers in JavaScript
- Find average of each array within an array in JavaScript
- Cumulative average of pair of elements in JavaScript
- MongoDB Aggregate to get average from document and of array elements?
- Maximum sum of n consecutive elements of array in JavaScript
- How to find the average of elements of an integer array in C#?
- How to get the first n values of an array in JavaScript?
- How to get only the first n% of an array in JavaScript?
- Rearranging elements of an array in JavaScript
- Parts of array with n different elements in JavaScript
- Minimum value among AND of elements of every subset of an array in C++
- Sum of distinct elements of an array - JavaScript
- Count of elements of an array present in every row of NxM matrix in C++
Advertisements