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

let numbers = [500, 400, 400, 375, 300, 350, 325, 300]

//* Average

const getAverage = (numbers) => {
 let sum = 0
 numbers.forEach((element) => sum = sum + element ) 
 
 return(sum/numbers.length)
}

//* Mode

//build an object that has each number as a key and number of occurrences as a value 
//E.g. [500: 1, 400: 2, 375:1, 300: 2, 350: 1, 325:1]
//In this example there are two modes.  The requirement is to return the first mode.

const getMode = (numbers) => {

  const obj = {};
    
  numbers.forEach((number, index) => {//not obj[number] return true if a number does not exist as a key in the object
    
    if (!obj[number]) { // does not exists therefore add it
      obj[number] = 1 
      
    } else {
      obj[number] += 1 // does exist so increment the count
      
    }
  }) 
  
   
  //iterate over array of number-objects and return the first mode
  let currentHighValue = 0
  let currentHighKey = -Infinity
  
  for (let key in obj) {
    const value = obj[key];

    if (value >= currentHighValue ) { 
      currentHighValue = value;        
      currentHighKey = key;
    }
  }
  
  return Number(currentHighKey)

} 

const statsFinder = (numbers) => {

 const average =  getAverage(numbers)
 const mode = getMode(numbers)

 return [average, mode]
}

function statsFinder(arr = []) { let mean = arr.reduce((acc, curr) => acc + curr, 0) / arr.length; let modeObj = {}; arr.forEach(el => { if (modeObj[el] === undefined) { modeObj[el] = { num: el, count: 1 }; } else { modeObj[el].count++; } }); let modeNum; Object.keys(modeObj).forEach(el => { if (modeNum === undefined) { modeNum = modeObj[el]; return; } if (modeObj[el].count > modeNum.count) { modeNum = modeObj[el]; } else if (modeObj[el].count === modeNum.count) { if (arr.indexOf(modeObj[el].num) < arr.indexOf(modeNum.num)) { modeNum = modeObj[el]; } } }); let mode = modeNum.num; 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;
function statsFinder(array) { // Write your code here let result // function to sum values of Array and duplicate values in Array const avgArray = (total, num) => total + num const dupArray = array.filter((item, index) => array.indexOf(item) !== index) // Calculate mean of the Array result = array.reduce(avgArray) / array.length return [result, dupArray[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 mean = array.reduce((acc,cur)=>acc+cur)/array.length
  let modes = []
  array.map((val,index)=>{
    let counts = 0;
    array.map((valTwo,indexTwo)=>{
      val == valTwo && counts ++ 
    });
    counts > 1 && modes.push(val);
  })
  return [mean,modes[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 mean = array.reduce((a,b)=> a+b,0)/array.length
const mode= […new Set(array)].map(el => [el, array.filter(x => x === el).length]).reduce((acc, cur) => acc[1] >= cur[1] ? acc : cur)[0]
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;

function statsFinder(array) { // Write your code here var storedArray = array; var sum = 0; array.forEach((num) => {sum += num}); var average = sum/array.length; const count = {}; array.forEach(function(e) { if(count[e] === undefined) { count[e] = 0 } count[e] += 1 }) var bestElement = 0; var bestCount = 0; Object.entries(count).forEach(([k,v]) => { if (v >= bestCount){ bestElement = k; bestCount = v; } }); var mode = parseInt(bestElement); return [average, mode]; } console.log(statsFinder([500, 400, 400, 375, 300, 350, 325, 300])) // Leave this so we can test your code: module.exports = statsFinder;

JavaScript challenge: Calculate the Mean and Mode #get-help:javascript

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

  let sum = 0;
  let mean = 0;
  let mode = [ ];

  for (let i = 0; i < array.length; i++) {
    sum += array[i];
  }
  mean = sum / array.length;

  const obj = {};
  array.forEach((key) => {
    if (!obj[key]) {
      obj[key] = 1;
    } else {
      obj[key] += 1;
    }
  })
  
  let highestValue = 0;
  let highestValueKey = 0;
  
  for (let key in obj) {
    let value = obj[key];
    if (value >= highestValue) {
      highestValue = value;
      highestValueKey = Number(key);
    }
  }
  mode = highestValueKey;
  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;
function statsFinder(array) {
  // Write your code here
  let mean = array.reduce((a, b) => a + b) / array.length;

  const comparisons = [];
  const compared = [];

  array.forEach(number => {
    if (!compared.includes(number)) {
      let occurences = array.filter(digit => digit === number).length;
      comparisons.push([number, occurences]);
      compared.push(number);
    }
  });

  let max = 0;
  let mode;
  comparisons.forEach(comparison => {
    const [number, occurence] = comparison;
    if (occurence > max) {
      max = occurence;
      mode = number;
    }
  });  

  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;

function statsFinder(array) {

let avg = 0;
let obj = {}
let counter = 0;
let mode = [0, 0]
while (counter < array.length) {
//Count average
avg += array[counter];
//Add occurences for each value into an object
obj[array[counter]] = (obj[array[counter]] || 1) + 1
// if prev value occured less times than this one, than add current value and its occurence count to the variable
if (mode[1] < obj[array[counter]]) mode = [array[counter], obj[array[counter]]]
counter++
}

return [avg / array.length, mode[0]]
}

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

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

Please, let me know the most optimal solution. If I’m not mistaken this function will be O(n) time complexity and O(n) space complexity

function statsFinder(array) {
  // Write your code here
  let modes = [];
  let mean = 0;

  for (let num of array) {
    mean += num;
    const index = modes.findIndex(n => n[0] === num)
    if (index === -1) {
    modes.push([num, 1]) } else {
      modes[index] = [num, modes[index][1] +1];
    }
  }

  return [mean / array.length, modes.sort((a, b) => b[1]-a[1])[0][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) {
// Write your code here
const arr1 = ;
const sum = array.reduce((a,b) => a + b,0);
const avg = sum / array.length
arr1.push(avg)

const numObj = {}
let highestValue = 0;
let highestValueKey = 0;

for(var i = 0; i < array.length; i++){
var currentNum = array[i]
if(numObj[currentNum]){
numObj[currentNum]++
}else{
numObj[currentNum] = 1
}
}
console.log(numObj)
for(let key in numObj){
const currentVal = numObj[key]
const currentKey = key
if(currentVal >= highestValue){
highestValue = currentVal
highestValueKey = currentKey
}
}
arr1.push(parseInt(highestValueKey))
return arr1
}

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 acum = 0 let times_repeated = {} let most_repeated = "" for(let i of array) { acum += parseInt(i) if(typeof times_repeated[i] == 'undefined') times_repeated[i] = 0 times_repeated[i]++ if(most_repeated === "" || times_repeated[most_repeated] < times_repeated[i]) { most_repeated = i } } return [(acum/array.length), most_repeated] } 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 sum = 0,
    counts = {},
    maxCount = 0,
    maxValue;
  array.forEach((val) => {
    sum += val;
    counts[val] = ++counts[val] || 1;
    if (counts[val] > maxCount) {
      maxCount = counts[val];
      maxValue = val;
    }
  });
  return [sum / array.length, maxValue];
}

function statsFinder(array) {
return [array.reduce((a, c) => a+c,0)/array.length, […array].sort((a, b) => array.filter(e => e==b).length-array.filter(e => e==a).length)[0]];
}

Time Complexity: O(n)
Space Complexity: O(1) for mean, O(n) for mode
In addition, each calculation requires only a single pass through the array, and meanFinder has an early exit for arrays of length 0.

const statsFinder = array => [meanFinder(array), modeFinder(array)]

const meanFinder = array => array.length ? array.reduce((acc, curr) => acc + curr, 0) / array.length : 0

const modeFinder = array => {
  const freqMap = {}
  let mode = 0;
  let currentMaxCount = 1;
  array.forEach(num => {
    freqMap[num] = freqMap[num] + 1 || 1
    if (freqMap[num] > currentMaxCount) {
      mode = num
      currentMaxCount = freqMap[num]
    }
  })
  return mode
}

I believe the mode finding part wouldn’t isolate which number occurs the most, but rather, whichever number first occurs more than 1 time.

1 Like
function statsFinder(array) { let result = []; let sum = 0; let arr = []; for(let i = 0; i < array.length; i++) { sum += array[i]; } let mean = sum / array.length; result.push(mean); for(let a of array){ let n = 0; for(let j = 0; j < array.length; j++) { if (a == array[j]) { n = n + 1; } } arr.push(n); } let index = arr.indexOf(Math.max.apply(null, arr)) result.push(array[index]); return result; }
function statsFinder(array) {
  let len = array.length
  const mean = array.reduce((acc, item) => acc + item) / len

  function backwardCounter(array, idx, value) {
    let acc = 1;
    while(idx--) {
      array[idx] === value ? acc++ : ''
    }
    return acc
  }

  const repeatedNumbers = []

  while(len--) {
    const value = array[len]
    const count = backwardCounter(array, len, value)
    if(count > 1) {
        repeatedNumbers[count] = value
    }
  }
  const mode = repeatedNumbers.pop() || 0

  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;
function statsFinder(array) { // Write your code here let SumArray=0 for (let i = 0; i < array.length; i++){ SumArray=SumArray+array[i] } const mode = {}; let max = 0, count = 0; for(let i = 0; i < array.length; i++){ const item = array[i] if(mode[item]){ mode[item]++ } else { mode[item] = 1 } if (count < mode[item]){ max = item count = mode[item] } } return [SumArray / array.length, max] } console.log(statsFinder([500, 400, 400, 375, 300, 350, 325, 300])) // Leave this so we can test your code: module.exports = statsFinder;

I wanted to write this code as if I was teaching it. The biggest challenge for me was trying to make the code without using 2 array methods or 2 loops even though it would have been done much faster. I am trying to improve my programming skills to reduce runtime.

Version with comments:

function statsFinder(array) { //======================================================================= // Variables //======================================================================= let sum = 0; let mode = 0; let previousRecord = 0; let obj = {}; //======================================================================= // For Loop //======================================================================= for(let i = 0; i < array.length; i++){ //===================================================================== // Variables //===================================================================== let currentValue = array[i] //===================================================================== // Obtain Sum of array //===================================================================== sum += currentValue; //===================================================================== // If the key has occurred one or more times add 1 occurance under in // object. //===================================================================== if(obj[array[i]] >= 1){ obj[array[i]] += 1 //=================================================================== // if the current key in the object has appeared the most times or // if the value in mode is less than the current value //=================================================================== if(obj[array[i]] > previousRecord || mode < currentValue){ //================================================================= // record the amount of times the key had appeared in the object // and set mode as the new value //================================================================= previousRecord = obj[array[i]]; mode = currentValue; } } //===================================================================== // If key has yet to occur, add key to object at with 1 occurrance //===================================================================== else{ obj[array[i]] = 1; } } //======================================================================= // Return average and mode //======================================================================= return [sum/array.length, mode] //======================================================================= } console.log(statsFinder([500, 400, 400, 375, 300, 350, 325, 300])) // Leave this so we can test your code: module.exports = statsFinder;

Version without comments:

function statsFinder(array) { let sum = 0; let mode = 0; let previousRecord = 0; let obj = {}; for(let i = 0; i < array.length; i++){ let currentValue = array[i] sum += currentValue; if(obj[array[i]] >= 1){ obj[array[i]] += 1 if(obj[array[i]] > previousRecord || mode < currentValue){ previousRecord = obj[array[i]]; mode = currentValue; } }else{ obj[array[i]] = 1; } } return [sum/array.length, mode] } console.log(statsFinder([500, 400, 400, 375, 300, 350, 325, 300])) // Leave this so we can test your code: module.exports = statsFinder;