如何在 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