我遇到了一些问题,如何真正获得我所获得的地图的最大价值。现在,我的代码只显示每个键的实际计数值,我坚持尝试记录最大值,我认为在我的代码中发生的是for循环通过count [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]));
&#13;
答案 0 :(得分:1)
这个数组需要更多的计数。这个
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
&#13;
答案 1 :(得分:0)
我终于通过使用以下代码解决了这个问题:
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]));
非常感谢你的帮助:)。
答案 2 :(得分:0)
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