Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

การนับตัวเลขต่ำกว่า/สูงกว่าค่าที่กำหนดในอาร์เรย์ JavaScript

ภาพรวม

บทความนี้สาธิตวิธีนับจำนวน Element ในอาร์เรย์ที่น้อยกว่า (Below) และมากกว่าหรือเท่ากับ (Par/Above) ค่าที่กำหนด

ตัวอย่าง

Array: [54,54,65,73,43,78,54,54,76,3,23,78]
Threshold 50: Below=3 (43,3,23), Par=9
Threshold 60: Below=7, Par=5
Threshold 70: Below=8, Par=4

การนำไปใช้

const belowParNumbers = (arr, num) => {
  return arr.reduce((acc, val) => {
    const isBelow = val < num;
    acc[isBelow ? 'below' : 'par']++;
    return acc;
  }, { below: 0, par: 0 });
};

console.log(belowParNumbers(array, 50));
console.log(belowParNumbers(array, 60));
console.log(belowParNumbers(array, 70));

ผลลัพธ์

{ below: 3, par: 9 }
{ below: 7, par: 5 }
{ below: 8, par: 4 }

วิธีการทันสมัย

const countBelowPar = (arr, threshold) => ({
  below: arr.filter(x => x < threshold).length,
  par: arr.filter(x => x >= threshold).length
});

// Single Pass (เร็วกว่า)
const countBelowParSinglePass = (arr, threshold) => 
  arr.reduce((acc, val) => {
    acc[val < threshold ? 'below' : 'par']++;
    return acc;
  }, { below: 0, par: 0 });

// ใช้ Sort + Binary Search (สำหรับ Query หลายครั้ง)
const createThresholdCounter = (arr) => {
  const sorted = [...arr].sort((a, b) => a - b);
  return (threshold) => {
    const idx = sorted.findIndex(x => x >= threshold);
    return idx === -1 ? { below: arr.length, par: 0 } 
         : { below: idx, par: arr.length - idx };
  };
};

การขยาย: Multiple Thresholds (Histogram)

const histogram = (arr, bins = 10) => {
  const min = Math.min(...arr);
  const max = Math.max(...arr);
  const binSize = (max - min) / bins;
  
  return Array.from({ length: bins }, (_, i) => {
    const low = min + i * binSize;
    const high = min + (i + 1) * binSize;
    return {
      range: `[${low.toFixed(1)}, ${high.toFixed(1)})`,
      count: arr.filter(x => x >= low && (i === bins - 1 ? x <= high : x < high)).length
    };
  });
};

การประยุกต์ใช้

  • Statistics: Percentiles, Quartiles
  • Monitoring: Alert Thresholds
  • Finance: Value at Risk (VaR)
  • Quality Control: Specification Limits
  • Game Analytics: Score Distribution