Calculate the Mean and Mode - Can't passed the test even though the result is correct

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;

link to my agony

pic:

I tried your mode function …
and found a case where it does not give the correct output:

function testModeOn(array) { 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 mode(0); } let stuff = [5, 5, 5, 5, 4, 4, 4, 4, 4, 3, 3, 3, 2, 2, 1, 6, 6, 6, 6, 6, 0, 0, 0, 0, 0]; // 4 fives, 5 fours, 3 threes, 2 twos, 1 ones, 5 sixes, 5 zeros console.log(testModeOn(stuff));

I haven’t actually done this code challenge … I don’t know what the answer is.

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) 
  }