hello guys,
I’ve been recently trying to solve some of the code challenge javascript (Calculate the Mean and Mode). Yet in this challenge, I got stuck to the point of being piss knowing that my solution did not passed the test even though the result has been met, it always ends up with 4/5.

I’ve tried everything I know about loopings, high order functions, arrays yet the latter didn’t let me pass. Guys I need your help with this.

function statsFinder(array) {
// MEAN
const mean = array.reduce((c1, c2) => {
return c1 + c2;
});
const meanResult = mean / array.length;
const meanArr = [];
meanArr.push(meanResult);
// MODE
function mode(index) {
const sortedArr = array.sort((a, b) => {
return a < b;
});
const modeArr = [];
const modeCompute = sortedArr.sort((c1, c2) => {
if (c1 === c2) {
modeArr.push(c1)
}
})
return modeArr[index]
return modeCompute
}
return meanArr.concat(mode(0))
}
console.log(statsFinder([500, 400, 400, 375, 300, 350, 325, 300]))
// Leave this so we can test your code:
module.exports = statsFinder;

Consider the stated requirement if there are more than one modes, the one that comes first in the list is the one to return. That means we should not sort the array.

Later

Having looked at this problem for a minute, we conclude that it is a two step undertaking. The first step will be to create a histogram, the order of which won’t matter. The next step would be to walk backwards through the array so that the eventual mode will be from the front, hence, the first. Is this a theory worth exploring?

Even later

How to create a histogram in JavaScript

There are a number or ways, but it boils down to this,

const hist = {}
for (let x of array) {
hist[x] = 1 + (hist[x] || 0)
}