- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Average with the Reduce Method in JavaScript
We are required to write a JavaScript function that takes in array of Numbers. The function should calculate the average of all the numbers in the array.
The only condition for us is that we have to do this using Array.prototype.reduce() method.
Example
const arr = [129, 139, 155, 176]; const calculateAverage = (arr = []) => { const reducer = (acc, value, index, array) => { let val = acc + value; if (index === array.length - 1) { return val / array.length; }; return val; }; const res = arr.reduce(reducer, 0); return res; }; console.log(calculateAverage(arr));
Output
And the output in the console will be −
149.75
- Related Articles
- How to apply the reduce method for objects in JavaScript?
- Sorting Array with JavaScript reduce function - JavaScript
- Finding the product of array elements with reduce() in JavaScript
- JavaScript reduce sum array with undefined values
- Reduce array in JavaScript
- How to write the factorial function with reduce and range in JavaScript?
- C# Average Method
- Average Profit Method
- IntStream average() method in Java
- LongStream average() method in Java
- DoubleStream average() method in Java
- How to reduce arrays in JavaScript?
- How to reduce the color using Iterator Method in OpenCV?
- Reduce an array to groups in JavaScript
- Return Largest Numbers in Arrays passed using reduce method?

Advertisements