Last Updated on April 29, 2024 by Roshan Parihar
To filter an array in JavaScript, use the filter()
function and pass the condition to filter out the array.
The filter() filters out the array according to the condition applied. Let’s find out with the examples given below.
How Javascript Filter an Array Using filter()
Function
If you want to filter an array using JavaScript, you have to declare two functions. 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.
Example 1
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 passes the first function as an argument.
When you click the above-given button, it executes the checkCount()
to give filtered array items using the filter()
.
By User Input Value Using Input Box
You can also use the input box to get users’ input and filter an array according to the specified value. The one thing you have to do is to get the value of the input box in the first function. After that, declare the second function containing the filter()
function to filter an array according to condition.
Example 2
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. It filters out an array according to the specified value in the input box.
You May Also Like to Read