JavaScript example to filter an array depending on multiple checkbox conditions.

JavascriptWeb DevelopmentObject Oriented Programming

Following is the code to filter an array depending on multiple checkbox condition using JavaScript −

Example

 Live Demo

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</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>Filter an array depending on multiple checkbox conditions</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()" />Number should be greater than 50<br />
<input type="checkbox" class="check" onclick="filterArr()" />Number should divide by 5<br />
<input type="checkbox" class="check" onclick="filterArr()" />Number should divide by 3<br />
<h3>tick the above checkbox to apply filter to the array above</h3>
<script>
   let resEle = document.querySelector(".result");
   let checkEle = document.querySelectorAll(".check");
   let arr = [22, 10, 50, 30, 90, 33, 80, 75, 33, 99, 150, 105];
   let resArr = arr;
   function filterArr() {
      checkEle.forEach((item, index) => {
         if (item.checked && index == 0) {
            resArr = resArr.filter((num) => num > 50);
            resEle.innerHTML = resArr;
         }
         else if (item.checked && index == 1) {
            resArr = resArr.filter((num) => num % 5 == 0);
            resEle.innerHTML = resArr;
         }
         else if (item.checked && index == 2)
         resArr = resArr.filter((num) => num % 3 == 0);
         resEle.innerHTML = resArr;
      });
   }
</script>
</body>
</html>

Output

The above code will produce the following output −

On ticking some of the checkbox −

raja
Published on 18-Jul-2020 08:24:53
Advertisements