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;
Do the test cases tell you what to return when they run?
If they are expecting a number then give them a number if the length of the modes array is equal to 1, otherwise pass an array. See if that works. Maybe none of the tests cases have more than one mode?
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];
}
}
}