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 (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 (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 (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

Learn more about how to use this guide.

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]
}
1 Like
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]
}
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[1] > a[1] ? e : a)[0];
  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[0]]

}

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) {
  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[1] >= mode.val) {
    mode.val = el[1];
    mode.index = el[0];
  }});
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;

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()? :slight_smile:

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];
}