Siegfried Siegfried - 1 month ago 18
Javascript Question

Calculating Mode with Javascript

I am having some problems how to actually get the biggest value of the map I have gotten. Right now, my code only displays the actual counted values of each key, I am stuck at trying to log the max, what I think happens in my code, is the for loop goes through the counts[key] array, but it will remain at 1, which is the first value and stops, because the only number that is logged is 1. I am not expecting the actual answer, maybe some tips and hints that would lead me the right way. Thanks in advance.



var Mode = function(data) {
var counts = {};
for (let i = 0; i < data.length; i++) {
counts[data[i]] = (counts[data[i]] + 1) || 1;
}
for (var key in counts) {
if (counts.hasOwnProperty(key)) {
var maxValue = Math.max(counts[key]);
}
}
return maxValue;
}
console.log(Mode([1, 5, 2, 3, 3, 4, 4, 4]));




Answer

I have finally solved this problem by using the following code:

var Mode = function(data) {
var counts = {};
for (let i = 0; i < data.length; i++) {
    counts[data[i]] = (counts[data[i]] || 0) + 1
}
var max = 0;
var values = [];
for (var key in counts) {
    if (counts.hasOwnProperty(key)) {
        if (counts[key] > max) {
            max = counts[key];
            values = [key];
        } else if (counts[key] === max) {
            max = counts[key];
            values.push(key);
        }
    }
}
return "The highest value is " + values.join(", ") + " with a count of " + max;
}
console.log(Mode([1, 2, 3, 3, 4, 4]));

Thanks a lot for your help :).