DEV Community

Cover image for Elegant way to Calculate Mean and/or Mode
Stanley Nadar
Stanley Nadar

Posted on

Elegant way to Calculate Mean and/or Mode


As part of the challenges, I came across this code challenge to 'Calculate Mean and Mode.' It appeared quite simple while reading the problem statement, but getting started raised a number of questions. As a result, I created this blog to share my experiences as I worked through the challenge.


Create a statsFinder() function that takes in a list of numbers and returns a list containing the mean and mode, in that order. As a reminder, the mean is the average of the values and the mode is the most occurring value. If there are multiple modes, return the mode that occurs first. Make sure that you write your functions and find these answers from scratch – don’t use imported tools!
For example, statsFinder([500, 400, 400, 375, 300, 350, 325, 300]) should return [368.75, 400]


Image representing the entire code
You can approach this challenge in a variety of ways, whether you're a beginner, intermediate, or pro; what matters is that you approach it by adhering to these fundamental principles (feel free to add more):

  1. Produce less code
  2. It should be simple to understand.
  3. Insert 'Single' or 'Multi-line' comments as needed.

My Approach

When attempting to solve problems, I have 99.99% faith in my gut. When I looked at the challenge, I actually realized two things:

  1. Sum of array
  2. Find duplicates and print the first occurrence (regardless of the length)

Ways to solve

My initial thoughts were to use for ... loop however then realized this could be solved in short time using Array methods, thus use of .filter() and .reduce()


Below is the solution I recommended:

function statsFinder(array) {
  // Check array length return error statement
  if (array.length === 0) return `Input error: argument is empty`
  // Arrow function to derive the sum of all values in the array
  const avgArray = (total, val) => total + val

    Below lines of code calculates mean 
    by dividing the result of .reduce() method 
    while mode arrow function to find duplicates
    using .filter() method
  const mean = array.reduce(avgArray) / array.length 
  const mode = array.filter((val, index) => array.indexOf(val) !== index)
  return [mean, mode[0]]
Enter fullscreen mode Exit fullscreen mode

Give it a try:

console.log(statsFinder([500, 400, 400, 375, 300, 350, 325, 300])) // [378.5, 400]
Enter fullscreen mode Exit fullscreen mode

Useful links


Try the code:

Top comments (0)