# JavaScript Challenge - Calculate the Mean and Mode, Calculate the Mean and Mode

This community-built FAQ covers the “Calculate the Mean and Mode” code challenge in JavaScript. You can find that challenge here, or pick any challenge you like from our list.

## Top Discussions on the JavaScript challenge Calculate the Mean and Mode

There are currently no frequently asked questions or top answers associated with this challenge – that’s where you come in! You can contribute to this section by offering your own questions, answers, or clarifications on this challenge. Ask a question or post a solution by clicking reply ( ) below.

If you’ve had an “aha” moment about the concepts, formatting, syntax, or anything else with this challenge, consider sharing those insights! Teaching others and answering their questions is one of the best ways to learn and stay sharp.

## Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply ( ) below!
You can also find further discussion and get answers to your questions over in #get-help.

Agree with a comment or answer? Like ( ) to up-vote the contribution!

Need broader help or resources? Head to #get-help and #community:tips-and-resources. If you are wanting feedback or inspiration for a project, check out #project.

Looking for motivation to keep learning? Join our wider discussions in #community

Found a bug? Report it online, or post in #community:Codecademy-Bug-Reporting

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!

``````function statsFinder(array) {
const add = (a, b) => a + b
const mean = array.reduce(add) / array.length
const hist = {}
for (let x of array) {
hist[x] = 1 + (hist[x] || 0)
}
let mode = ''
let count = 0
for (let x of array.reverse()) {
if (hist[x] >= count) {
mode = x
count = hist[x]
}
}
return [mean, mode]
}
``````
4 Likes
``````function statsFinder(array) {
// Write your code here
var meanresult = 0
var moderesult = 0
var modemaxcount = 0
var md = {}

array.forEach((array)=>{
meanresult = meanresult + array
if(array in md)
{
md[array]++

If(md[array]>modemaxcount) {
moderesult = array
modemaxcount = md[array]
}
else md[array]++
}
else md[array] = 0
})
meanresult = meanresult/array.length

return [meanresult, moderesult]
}

console.log(statsFinder([500, 400, 400, 375, 300, 350, 325, 300]))

// Leave this so we can test your code:
module.exports = statsFinder;
``````
``````function statsFinder(array) {
var sum = 0;
const modes = {};

array.map((el, index) => {
sum += el;

if (!modes[el]) {
modes[el] = { count: 1};
} else {
modes[el] = {count: modes[el].count + 1};
}
})

const mean = sum / array.length;
var highestKey = null;
var highestCount = -Infinity;

for (var key in modes) {
const value = modes[key];
if (value.count >= highestCount) {
highestKey = parseInt(key);
highestCount = parseInt(value.count);
}
}

return [mean, highestKey]
}
``````
1 Like
``````function statsFinder(array) {
// Write your code here
let sortedAscArray = array.sort((a,b)=>a-b);
let mean = sortedAscArray.reduce((accl, val) => {
return accl + val;
}) / array.length;
let mode = new Map(); // [val:x, occurences:y]
for (let i = 0; i < array.length -1; i++) {
let occurences = 1;
let item = sortedAscArray[i];
if (mode.has(item)) {
occurences = mode.get(item) + 1;
}
mode.set(item, occurences);
}
/*
let highestMode = -1;
mode.forEach((val, key) => {
if (key > highestMode) {
highestMode = key;
}
});
*/

let highestMode = [...mode.entries()].reverse().reduce((a, e ) => e > a ? e : a);
console.log(highestMode);

return [mean, highestMode];
}

console.log(statsFinder([500, 400, 400, 375, 300, 350, 325, 300]))

// Leave this so we can test your code:
module.exports = statsFinder;
``````
``````function statsFinder(array) {
let nrMap = new Map();
let sum = 0;
array.forEach((nr) => {
nrMap.set(nr, nrMap.get(nr) + 1 || 1);
sum += nr;
});
let mode, maxCount = 0;
for (const [value, count] of nrMap) {
if (count > maxCount) {
mode = value;
maxCount = count;
}
}
return [sum / array.length, mode];
}
``````

function statsFinder(array) {
// Write your code here

let arr = ;

let sum = array.reduce((a, c) => a + c,0);

const obj = {};
const tempArr = ;
for(let i = 0; i < array.length; i++){
if(obj[array[i]]){
obj[array[i]] ++;
!tempArr.length && tempArr.push(array[i])
}
else{
obj[array[i]] = 1
}
}

let res = sum / array.length;
return [res, tempArr]

}

console.log(statsFinder([500, 400, 400, 375, 300, 350, 325, 300]))

// Leave this so we can test your code:
module.exports = statsFinder;

1 Like
``````function statsFinder(array) {
const result = [];
const counts = {};
let mode = {'val' : 0, 'index' : 0};
const reducer = (previousValue, currentValue) => previousValue + currentValue;
result.push(array.reduce(reducer)/array.length);
array.forEach(num=>counts[num] = counts[num] ?
counts[num] + 1 : 1);
Object.entries(counts).forEach(function(el) {
if (el >= mode.val) {
mode.val = el;
mode.index = el;
}});
result.push(parseInt(mode.index));
return result;
}

console.log(statsFinder([500, 400, 400, 375, 300, 350, 325, 300]))

// Leave this so we can test your code:
module.exports = statsFinder;
``````

I separated the concerns by creating `.calculateMean()` and `.calculateMode()` functions to do just that.

function statsFinder(array) { // Write your code here // calculate mean const mean = calculateMean(array) // calculate mode const mode = calculateMode(array) return [mean, mode] } function calculateMean(array) { const sum = array.reduce((acc, n) => acc + n, 0) const mean = sum / array.length return mean } function calculateMode(array) { let frequencies = {} let highestFrequency = -Infinity let highestFrequencyKey = -Infinity for(let n of array) { frequencies[n] = frequencies[n] ? frequencies[n] + 1 : 1 if(frequencies[n] && frequencies[n] > highestFrequency) { highestFrequency = frequencies[n] highestFrequencyKey = n } } return highestFrequencyKey } console.log(statsFinder([500, 400, 400, 375, 300, 350, 325, 300])) // Leave this so we can test your code: module.exports = statsFinder;
2 Likes

There is no crime in writing functions inside the main function. This keeps them out of the global namespace and prevents possible collisions in global scope. Since the helper functions are dedicated to the parent function it makes perfect sense to include them inside it.

``````function foo (bar) {
function helperA (x) {

}
function helperB (x) {

}
//  code
}
``````

I’m a big fan of this simple form of encapsulation, since it makes the parent function both portable and free of dependencies.

1 Like

Fair points! I’d totally do that on a rewrite. And I suppose my code as-is only works because the helpers are hoisted up and, therefore, accessible inside the scope of `statsFinder()`? You’re right about the hoisting part. If they were function expressions they would have been uncallable from the main function. This brings up a good point to keep in mind… Always declare functions before their first call, then it won’t matter if they are declared or expressions.

JS allows a lot of little less than good habits to form if we let it. The strictness is up to us (unless using 'strict` mode) but not all that demanding. A few good habits can make us look strict, even when we’re not.

1 Like
``````function statsFinder(array) {
let mean = array.reduce((p, c) => p + c) / array.length;
let mode, modeObj = {};
array.forEach(el => modeObj[el] = (modeObj[el] || 0) + 1);
mode = array.reduce((p, c) => modeObj[c] > modeObj[p] ? c : p);
return [mean, mode];
}
``````

I tried to not use any array method (except length), as I wrongly understood the instruction ‘don’t use imported tools’ function statsFinder(array) { // Write your code here let sum = 0; let length = 0; let k=1; let modeoccurences = 1; let mode=array; for (let i=array.length-1; i>=0; i--) { sum = sum+ array[i]; length++; for (let j=i-1; j>=0; j--) { if (array[i]===array[j]) {k++} } if (k>modeoccurences) { modeoccurences=k; mode = array[i]; } } return [sum/length,mode]; } console.log(statsFinder([500, 400, 400, 375, 300, 350, 325, 300]))

Mine is a bit more verbose…

const statsFinder = numArr => { let numberObjects = []; // stats on each entry in 'arr' let numOccurances = []; // occurances of each entry let mode, mean; numArr.forEach((num, index)=>{ let numObj = {}; // create object for each number // Function for counting the occurances of each number, in order const numCount = (num) => { let count = 0; for (let i=0; i<numArr.length; i++) { num === numArr[i] ? count += 1 : count += 0; } numOccurances.push(count); // push to array of counts for sorting return count; // for assigning to object } let count = numCount(num); // count for each number numObj['number'] = num; // sets number value numObj['index'] = index; // sets index value to find it again numObj['occurances'] = count; // sets number of occurances numberObjects.push(numObj); // pushes object to array }) numOccurances.sort((a,b)=>b-a); // find the highest number of occurances... let maxOcc = numOccurances; // and save it to a variable // Iteration to find the first number-object with the highest count numberObjects.find(numObj => { if (numObj.occurances === maxOcc) { mode = numObj['number']; return mode; } }) // Just to update the object stats numberObjects.forEach(numObj => { const isMode = (num) => num === maxOcc; numObj['is mode?'] = isMode(numObj.occurances); }) // Calculate actual average mean = (numArr.reduce((a,b)=>a+b))/numArr.length; // Send it return [mean, mode]; } console.log(statsFinder([500, 400, 400, 375, 300, 350, 325, 300])) // Leave this so we can test your code: module.exports = statsFinder;
1 Like
function statsFinder(array) { let newArray=[] let sum=0 let occuredTimes=0 let occuringNums=[] let greatest=0 let final=[] for (let i=0; i<array.length; i++){ occuredTimes=0 sum+=array[i] for (let a=0; a<array.length; a++){ if (array[i]===array[a]){ occuredTimes++ } } occuringNums.push([array[i],occuredTimes]) } for (b=0; b<occuringNums.length; b++){ if (occuringNums[b]>greatest){ greatest=occuringNums[b] } } for (c=0; c<occuringNums.length; c++){ if (occuringNums[c]===greatest){ final.push(occuringNums[c]) } } newArray.push((sum/array.length)) newArray.push(final) return newArray } console.log(statsFinder([500, 400, 400, 375, 300, 350, 325, 300])) // Leave this so we can test your code: module.exports = statsFinder;

This is my code for the Calculate The Mean and Mode challenge in javascript. It works fine but it says "Tests failed to run due to an error: "Looks like your code is not compiling or not being exported with `module.exports = statsFinder`. Check for a syntax error. “. Check your code and try again.” I don’t get where I did wrong. Can someone please tell me where I am wrong?

Hello! Can you post a link to the exercise, please?

We have no access to the test cases so can only keep working at it until we pass them all. Look for every means possible to simplify, and study if there are any edge cases that might slip through.

function statsFinder(array) {
// Write your code here
var numMapping = {};
for(var i = 0; i < array.length; i++){
if(numMapping[array[i]] === undefined){
numMapping[array[i]] = 0;
}
numMapping[array[i]] += 1;
}
var greatestFreq = 0;
var greatestFreqNum =
var mode;

``````for(var prop in numMapping){
if(numMapping[prop] >= greatestFreq){
greatestFreqNum.push(prop)
greatestFreq = numMapping[prop];
}
}
greatestFreqNum.sort(function(a, b){return b - a});
mode = Number(greatestFreqNum)
``````

let total=0;

array.map((number)=>{
total += number
})
const mean = total/(array.length)
return [mean,mode]
}

console.log(statsFinder([500, 400, 400, 375, 300, 350, 325, 300]))

// Leave this so we can test your code:
module.exports = statsFinder;