Finding the mean and median were pretty easy, I was happy! This one is seeming to be a bit more difficult: finding the mode. The answer cannot be [10], it must be 10.
function mode(numbers) {
//declare variables
//array to be returned as answer
let modes = []
//count how many numbers in array
let count = []
let i;
let num;
//keep track of most consistent number
let max = 0;
for (i = 0; i < numbers.length; i++) {
num = numbers[i];
count[num] = (count[num] || 0) + 1;
if (count[num] > max) {
max = count[num];
}
}
for (i in count)
if (count.hasOwnProperty(i)) {
if (count[i] === max) {
modes.push(Number(i));
}
}
return modes;
Of course I broke something…
function mode(numbers) {
//declare variables
//array to be returned as answer
let modes = []
//count how many numbers in array
let count = []
let i;
let num;
//keep track of most consistent number
let max = 0;
for (i = 0; i < numbers.length; i++) {
num = numbers[i];
count[num] = (count[num] || 0) + 1;
if (count[num] > max) {
max = count[num];
}
}
for (i in count)
if (count.hasOwnProperty(i)) {
if (count[i] === max)
modes.push(Number(i));
else if (count[i].length === 1){
return count[i]
}
}
}
return modes
Thanks…I currently have this but it still gives me back an array if it is one number.
function mode(numbers) {
let modes = []
let count = []
let i;
let num;
let max = 0;
for (i = 0; i < numbers.length; i += 1) {
num = numbers[i];
count[num] = (count[num] || 0) + 1;
if (count[num] > max) {
max = count[num];
}
}
for (i in count){
if (count.hasOwnProperty(i)) {
if (count[i] === max) {
modes.push(Number(i));
return modes;
}
}else{
return count[i];
}
}
}
It isn’t there yet. I’m not sure if I need the else if statement or not.
Gonna just give this one up for the day and call it early. I guess I’ll come back tomorrow.