如何在 JavaScript 中使用百分位数公式计算给定数组中小于/等于给定值的数字个数?
本文将介绍如何使用百分位数公式计算给定数组中小于/等于给定值的数字个数。我们使用以下公式计算给定数组中小于或等于该数字的百分比:
Percentile = (n/N) * 100
其中,n 是小于 x 的值的个数,N 是值的总数。
示例 1
在本例中,我们使用 for 循环迭代数组,并检查每个元素的值是否小于、等于或大于给定的输入值。
const calculationPercentile = (inputArray, val) => {
let resultValue = 0;
for (let i in inputArray) {
resultValue = resultValue + (inputArray[i] < val ? 1 : 0) +
(inputArray[i] === val ? 0.5 : 0);
}
let displayResult = (resultValue / inputArray.length) * 100;
console.log("
The percentile value is ")
console.log(displayResult);
};
const inputArray = [3,4,5,6,7,8]
console.log("The array is defined as :", inputArray)
// calling the function calculationPercentile
calculationPercentile(inputArray, 6);
解释
步骤 1 − 定义一个数字数组和一个输入值。
步骤 2 − 定义一个名为 'calculationPercentile' 的函数,该函数接收一个数组和一个值作为输入。
步骤 3 − 在函数中,定义一个变量 'resultValue',用于保存数组中小于 inputValue 的数字的个数。
步骤 4 − 最后应用百分位数公式:(resultValue / inputArray.length) * 100 并显示结果。
示例 2
在本例中,我们使用 reduce() 方法遍历数字数组并将其转换为单个实体。
const calculationPercentile = (inputArray, inputValue) =>
(100 *
inputArray.reduce(
(tempValue, v) => tempValue + (v < inputValue ? 1 : 0) +
(v === inputValue ? 0.5 : 0),
0
)) /
inputArray.length;
const inputArray = [3,4,5,6,7,8]
console.log("The array is defined as :", inputArray)
let inputValue = 6
console.log("The array is defined as :", inputValue)
console.log("
The percentile value is ")
console.log(calculationPercentile(inputArray, inputValue))
解释
步骤 1 − 定义一个数字数组和一个输入值。
步骤 2 − 定义一个名为 'calculationPercentile' 的函数,该函数接收一个数组和一个值作为输入。
步骤 3 − 在函数中,使用 reduce() 方法获取数组中小于输入值的值,将该数字除以数组长度,再乘以 100。
步骤 4 − 调用函数并显示结果。
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP