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

การกรอง Array ตามเงื่อนไขหลาย Checkbox ใน JavaScript

การ Filter Array ตามเงื่อนไขหลายอย่างจาก Checkbox เป็นรูปแบบ UI ที่พบบ่อย ต้องจัดการ State ของ Checkbox และ Apply Filter แบบ Dynamic

ตัวอย่างโค้ด

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Multi-checkbox Filter</title>
  <style>
    body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
    .result, .sample { font-size: 18px; font-weight: 500; color: rebeccapurple; }
    .result { color: red; }
  </style>
</head>
<body>
  <h1>กรอง Array ตามเงื่อนไขหลาย Checkbox</h1>
  <div class="sample">[22,10,50,30,90,33,80,75,33,99,150,105]</div>
  <div class="result"></div>
  <br />
  <input type="checkbox" class="check" onclick="filterArr()" /> ตัวเลข > 50<br />
  <input type="checkbox" class="check" onclick="filterArr()" /> หาร 5 ลงตัว<br />
  <input type="checkbox" class="check" onclick="filterArr()" /> หาร 3 ลงตัว<br />
  <h3>ติ๊ก Checkbox เพื่อกรอง Array ข้างต้น</h3>
  <script>
    const resEle = document.querySelector(".result");
    const checkEle = document.querySelectorAll(".check");
    const arr = [22, 10, 50, 30, 90, 33, 80, 75, 33, 99, 150, 105];
    let resArr = [...arr]; // Copy array
    
    window.filterArr = function() {
      // เริ่มจาก array ต้นฉบับทุกครั้ง
      resArr = [...arr];
      
      checkEle.forEach((checkbox, index) => {
        if (checkbox.checked) {
          if (index === 0) {
            resArr = resArr.filter(num => num > 50);
          } else if (index === 1) {
            resArr = resArr.filter(num => num % 5 === 0);
          } else if (index === 2) {
            resArr = resArr.filter(num => num % 3 === 0);
          }
        }
      });
      
      resEle.innerHTML = resArr.join(", ");
    };
  </script>
</body>
</html>

⚠️ ปัญหาของโค้ดต้นฉบับและวิธีแก้

โค้ดต้นฉบับมี Bug: resArr ถูก Filter สะสม (Mutate) ทำให้ Uncheck Checkbox ไม่ย้อนกลับได้ โค้ดด้านบนแก้ไขโดย Reset resArr จากต้นฉบับทุกครั้ง

รูปแบบ Modern: Filter Functions Array

const filters = [
  { id: "gt50", label: "> 50", fn: n => n > 50 },
  { id: "div5", label: "÷5", fn: n => n % 5 === 0 },
  { id: "div3", label: "÷3", fn: n => n % 3 === 0 }
];

function applyFilters() {
  const activeFilters = filters
    .filter(f => document.getElementById(f.id).checked)
    .map(f => f.fn);
  
  const result = arr.filter(item => 
    activeFilters.every(fn => fn(item))
  );
  
  resEle.textContent = result.join(", ");
}

ผลลัพธ์

แสดงตัวเลขที่ผ่านเงื่อนไข Checkbox ที่ติ๊กไว้ (AND Logic - ต้องผ่านทุกเงื่อนไขที่เลือก)