Majorly JavaScript Array Filter Function is used to filter data from an array with the specified condition and create a new array. Here we do check the complete guide of JavaScript Filter Function by using some examples.
Example of JavaScript Array Filter Function
In this example, we create an array name age, where we push some numbers and add an input field to take user input to specify the condition. An example is referred from w3schools.com
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<p>Minimum age: <input type="number" id="ageToCheck" value="18"></p> <button onclick="myFunction()">Try it</button> <p>All ages above minimum: <span id="demo"></span></p> <script> var age = [32, 33, 12, 40]; function checkAdult(age) { return age >= document.getElementById("ageToCheck").value; } function myFunction() { document.getElementById("demo").innerHTML = age.filter(checkAdult); } </script> |
Live view:
See the Pen Example of JS filter function by Bikash Panda (@phpcodertech) on CodePen.
Code Explanations:
- Create a user input field where we take the number to compare with an existing array.
- Then we get the user input using the ID attribute and compare it with an array using the JS Filter function.
JavaScript How to Filter Array of Objects
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
const ids = [1, 4, 5], data = { records: [{ "userID": 1, "fname": "X", "lname": "Y" }, { "userID": 2, "fname": "A", "lname": "Y" }, { "userID": 3, "fname": "B", "lname": "Y" }, { "userID": 4, "fname": "C", "lname": "Y" }, { "userID": 5, "fname": "C", "lname": "Y" }] }; data.records = data.records.filter( i => ids.includes( i.userID ) ); console.info( data ); |
Output:
Here are the complete explanations of the JavaScript array filter method and JavaScript filter works with an example.
Also, the above code explains how to filter an array of objects using the JS filter method.
Also Check:
- How JavaScript For Loop Works (Complete Guide With Example)
- jQuery Signature Pad with saving As Image Using html2canvas
- Image Creation From User Input in PHP
- Get List of Holidays Using Google Calendar API
Happy Coding..!
2 Replies to “How Does JavaScript Array Filter Function work With Example”