
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
Find Average of Each Array Within an Array in JavaScript
We are required to write a function getAverage() that accepts an array of arrays of numbers and we are required to return a new array of numbers that contains the average of corresponding subarrays.
Let’s write the code for this. We will map over the original array, reducing the subarray to their averages like this −
Example
const arr = [[1,54,65,432,7,43,43, 54], [2,3], [4,5,6,7]]; const secondArr = [[545,65,5,7], [0,0,0,0], []]; const getAverage = (arr) => { const averageArray = arr.map(sub => { const { length } = sub; return sub.reduce((acc, val) => acc + (val/length), 0); }); return averageArray; } console.log(getAverage(arr)); console.log(getAverage(secondArr));
Output
The output in the console will be −
[ 87.375, 2.5, 5.5 ] [ 155.5, 0, 0 ]
Advertisements