Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
JavaScript example to filter an array depending on multiple checkbox conditions.
Following is the code to filter an array depending on multiple checkbox condition using JavaScript −
Example
<!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 −

Advertisements