In this tutorial, learn javascript filter an array method to get the required array. The short answer is to use the filter()
function and pass the condition to filter out the array.
It requires two functions, in which the first function contains the filter condition to apply to the array of items. Use the filter function by passing the conditional function as an argument of the filter()
.
How Javascript Filter an Array Using filter()
Function
You have to declare two functions to filter out the array in javascript. The first function should return the filter condition to apply to the array items. The second function should contain the filter()
and pass the first function as its argument.
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 the filtered array : <span id="myPara"></span></p> <button onclick="checkCount()" class="btn btn-primary">Filter Count</button> |
Output
Click the below button to get the filtered array :
The above example contains an array in a variable count
. After that, it creates a function reqCount()
inside which it returns a condition that the values should be greater than 20. The second function is checkCount()
uses the filter()
and pass the first function as an argument.
When you click the above-given button, it executes the checkCount()
to give filtered array items. Javascript filter an array using the filter()
.
By User Input Value Using Input Box
For javascript filter an array according to the user input value, you have to use an input box to get user input. You have to use the same thing used in the above example.
The one thing you have to do is to get the value of the input box and change the manual value with it. It means, the first function containing the filter condition(e.g. UserreqCount()
).
1 2 3 4 5 6 7 8 9 10 11 12 |
<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 :
The above example contains an input box and a button. You can enter any value in the input box and click the button to filter array values in javascript.
You May Also Like to Read