我正在尝试计算数组的mode
,但是我想排除0
这是我的代码:
const数据= [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]
感谢您的时间。
答案 0 :(得分:3)
您可以简单地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);
答案 1 :(得分:0)
我只是想分享一种无mode
/ for
循环的forEach
计算方法。
相关文档:
const counted = [0, 0, 0, 4, 4, 2, 3, 2, 0]
.filter(element => element)
.reduce(
(accumulator, currentValue) =>
({
...accumulator,
[currentValue]: (accumulator[currentValue] || 0) + 1
}),
{}
);
const maxCount = Math.max(...Object.values(counted));
const mode = Object.keys(counted).filter(key => counted[key] === maxCount);
console.log(mode);