计算模式与Javascript

Calculating Mode with Javascript

本文关键字:Javascript 模式 计算      更新时间:2023-09-26

我遇到了一些问题,如何实际获得我所获得的地图的最大价值。现在,我的代码只显示每个键的实际计数值,我被困在试图记录最大值,我认为在我的代码中发生的事情是,for循环遍历counts[key]数组,但它将保持在1,这是第一个值并停止,因为唯一记录的数字是1。我并不期待真正的答案,也许一些提示和提示会引导我走上正确的道路。提前谢谢。

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

您需要在这个数组中增加count的个数。试试这个

var max =0;
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)) {
             if(counts[key] > max){max=counts[key];}
          
        }
    }
    return max;
}
console.log(Mode([1, 5, 2, 3, 3, 4,4, 4, 4]));//4 is a higher count
console.log(Mode([ 5,5,5,5,5,5,5, 2, 3, 3, 4, 4]));//5 is higher count

我终于用下面的代码解决了这个问题:

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

谢谢你的帮助。

function mode(numbers) {
    // as result can be bimodal or multi-modal,
    // the returned result is provided as an array
    // mode of [3, 5, 4, 4, 1, 1, 2, 3] = [1, 3, 4]
    var modes = [], count = [], i, number, maxIndex = 0;
 
    for (i = 0; i < numbers.length; i += 1) {
        number = numbers[i];
        count[number] = (count[number] || 0) + 1;
        if (count[number] > maxIndex) {
            maxIndex = count[number];
        }
    }
 
    for (i in count)
        if (count.hasOwnProperty(i)) {
            if (count[i] === maxIndex) {
                modes.push(Number(i));
            }
        }
 
    return modes;
}
console.log(mode([1, 2, 4, 1, 4, 4]));   // 4
console.log(mode([1, 20, 3, 20, 4, 20])); // 20