You can filter an array using the Javascript filter array method. The Javascript filter array method requires an array containing some items to filter.
It requires two functions, in which the first function contains the filter condition to apply to the array items. Use the filter function by passing the conditional function as an argument of the filter()
.
Example to Get filter an array Using Javascript filter array
Here in the below example, there are two functions – reqCount() and checkCount(). The reqCount() contains the condition by which the array gets filtered and the second function checkCount() contains the filter function with an argument as the previous function.
1 2 3 4 5 6 7 8 9 10 11 | <script> var count = [20, 16, 40, 60, 12, 10]; function reqCount(mycount){ return mycount >= 20; } function checkCount(){ document.getElementById("myPara").innerHTML = count.filter(reqCount); } </script> <p>Click the below button to get filtered array : <span id="myPara"></span></p> <button onclick="checkCount()" class="btn btn-primary">Filter Count</button> |
Output
Click the below button to get filtered array :
Click the above given button to run the checkCount() which gives out the filtered array items using the filter().
Example to Get filter an array by Using Javascript filter array and User Input Value
If you want to filter an array according to the user input value, you have to use an input box to get user input. Pass the value of the user input value as the value of the function containing the filter condition(e.g. UserreqCount).
1 2 3 4 5 6 7 8 9 10 11 12 13 | <script> var count = [20, 16, 40, 60, 12, 10]; function UserreqCount(Usercount){ return Usercount >= document.getElementById("myInput").value; } function UsercheckCount(){ document.getElementById("ParaResult").innerHTML = count.filter(UserreqCount); } </script> <input type="text" placeholder="Enter the value" id="myInput"/> <button onclick="UsercheckCount()" class="btn btn-primary">Filter Count</button> <p>The result of entered value for Javascript filtered array : <span id="ParaResult"></span></p> |
Output
The result of entered value for Javascript filtered array :
Click the button given above to get the Javascript filter array values using user input value.