Practice
JavaScriptData StructuresReactConcepts
Sign in
← Back to problems

Average

Working With Arraysmedium

Course · Section 11: Working With Arrays · Lecture 156: Data Transformations: map, filter, reduce

Implement `average(nums)` returning the mean of the array, or `0` for an empty array.

Sample tests

Input: average([2,4,6])
Output: 4
Input: average([])
Output: 0

+ 1 hidden test run on Submit.

Hints

Common pitfalls
  • Dividing by zero on an empty array yields NaN.

Learning resources

  • MDN: Array.prototype.reduce
Visualize this concept: map, filter, and reduce →
Approach & explanation (try first)

Return 0 for an empty array, otherwise the sum divided by the count.

Loading...
⌘/Ctrl + Enter

Run your code to see results.