Introduction
As part of the codecademy.com 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.
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]
Solution
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):
- Produce less code
- It should be simple to understand.
- 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:
- Sum of array
- 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()
Solution
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]]
}
Give it a try:
console.log(statsFinder([500, 400, 400, 375, 300, 350, 325, 300])) // [378.5, 400]
console.log(statsFinder([]))
Useful links
- .filter() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
- .reduce() https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
Challenge
https://www.codecademy.com/code-challenges/code-challenge-calculate-the-mean-and-mode-javascript
Try the code: https://codepen.io/istealersn-dev/pen/wvjJxRX
Top comments (0)