我正在尝试计算我可以执行的数组的模式
,但我想排除 0
这是我的代码:
常量数据 = [0, 0, 0, 4, 4, 2, 3, 2, 0];
function mode(numbers) {
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;
}
mode(datas); // output : [0] and I want [4] [2]
感谢您抽出时间。
最佳答案
您可以简单地filter
出零:
datas = [0, 0, 0, 4, 4, 2, 3, 2, 0];
function mode(numbers) {
// we don't want to consider zeros
// so filter them out
numbers = numbers.filter(function(n) { return n !== 0 });
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(datas)) // output : [4] [2]
如果您使用的是 ES6,则可以使用箭头函数语法:
numbers = numbers.filter(n => n !== 0);
关于javascript - 我如何计算数组的模式并忽略数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52825619/