How to Filter an Array in Javascript Examples

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


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


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