JavaScript中数据集的均值模式是否相等
我们需要编写一个JavaScript函数,该函数接受一组已排序的数字。函数应计算数据集的平均值和众数。然后,如果均值和众数相等,则函数应返回true,否则返回false。
例如-
如果输入数组是-
const arr = [5, 3, 3, 3, 1];
那么此数组的输出应为true,因为此数组的均值和中位数均为3。
示例
以下是代码-
const arr = [5, 3, 3, 3, 1];
mean = arr => (arr.reduce((a, b) => a + b))/(arr.length);
mode = arr => {
let obj = {}, max = 1, mode;
for (let i of arr) {
obj[i] = obj[i] || 0;
obj[i]++
}
for (let i in obj) {
if (obj.hasOwnProperty(i)) {
if ( obj[i] > max ) {
max = obj[i]
mode = i;
}
}
}
return +mode;
}
const meanMode = arr => mean(arr) === mode(arr)
console.log(meanMode(arr));输出结果以下是控制台上的输出-
true
热门推荐
10 祝孙辈生日祝福语简短
11 恋人跨年祝福语大全简短
12 考大学敬酒简短祝福语
13 开工投产大吉祝福语 简短
14 偶然结婚祝福语朋友简短
15 感谢学长学姐祝福语简短
16 戏精的祝福语简短
17 我要结婚祝福语简短
18 婚前女儿生日祝福语简短