In: Computer Science
The code to create a Search/Filter Data with Javascript or html from html page.
We use filter() method of an array to filter elements of the array
The filter() method creates an array filled with all array elements that pass a test (provided as a function).
And to search element in the array we use find() method
The find()
method returns the value of the first
element in an array that pass a test (provided as a function).
Here is the basic use of find and filter methods.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Filter</title>
</head>
<body>
<h3>Filter</h3> <br>
<input type="radio" name="filterItem" value="all" onclick="filterFunc('all')">All <br>
<input type="radio" name="filterItem" value="even" onclick="filterFunc('even')">Even <br>
<input type="radio" name="filterItem" value="odd" onclick="filterFunc('odd')">Odd <br>
<input type="radio" name="filterItem" value="divBy3" onclick="filterFunc('divBy3')">Divisible by 3 <br>
<h3>Items</h3>
<div id="filterOutput">
</div>
<h3>Search</h3>
<input type="search" name="search" placeholder="Search" value="" id="searchList" onkeyup="searchFunc(document.getElementById('searchList').value)">
<div id="searchOutput">
</div>
<script>
var mylist=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15];
//A simple function to display the List on the Html page
function viewList(dispList){
document.getElementById('filterOutput').innerHTML="";
dispList.forEach(x => {
document.getElementById('filterOutput').innerHTML+=x+"<br>";
});
}
// Just using the list of no from 1 to 15 and filtering numbers in list as even , odd or div by 3
viewList(mylist);
function filterFunc(option){
switch(option){
case 'all':{viewList(mylist);break;}
case 'even': {
viewList(mylist.filter(i=>{
return i%2==0;
}));
break;
}
case 'odd': {
viewList(mylist.filter(i=>{
return i%2!=0;
}));
break;
}
case 'divBy3': {
viewList(mylist.filter(i=>{
return i%3==0;
}));
break;
}
}
}
//Displays Found if the no entered is in the list
function searchFunc(s){
s=parseInt(s);
result=mylist.find((i)=>{
return i==s;
});
if(result){
document.getElementById("searchOutput").innerHTML='Found';
}
else{
document.getElementById("searchOutput").innerHTML='Not Found';
}
}
</script>
</body>
</html>