In this tutorial, we will learn about the JavaScript Array filter() method with the help of example programs.
The filter() method returns a new array with all elements that match a certain condition defined in a callback function.
It executes the callback function on every element in the array and returns a new array of all elements for which the function returns true.
Array.filter() method is useful when we want to find or extract all elements in an array that meets a specific condition and copy them into a new array.
For example, we can filter an array of numbers that numbers are bigger than 3 using the following code.
Program code 1:
<script> const numbers = [1, 2, 3, 4, 5, 6, 7, 8]; // Create a function to check numbers that are bigger than 3. function checkBigger(num) { if (num > 3) return true; else return false; } // Create a new array by filtering bigger numbers from the numbers array. const biggerNumbers = numbers.filter(checkBigger); document.write(biggerNumbers); </script>
Output: 4,5,6,7,8
In this example, the callback function checks in each iteration to see if the element in the array, represented by a parameter num, is greater than 3.
If the number is greater than 3, the callback function returns true and copy that element into a new array for which function returns true. We can see this process in the below diagram.
Thus, Array.filter() method provides a useful way of finding all the truth values from an array. This method does not change the original array on which it is called.
JavaSctipt Array filter() Syntax
The general syntax of the filter() method in JavaScript is:
// Arrow function arr.filter((element) => { /* ... */ } ) arr.filter((element, index) => { /* ... */ } ) arr.filter((element, index, array) => { /* ... */ } ) // Callback function arr.filter(callbackFn) arr.filter(callbackFn, thisArg) // Inline callback function arr.filter(function(element) { /* ... */ }) arr.filter(function(element, index) { /* ... */ }) arr.filter(function(element, index, array){ /* ... */ }) arr.filter(function(element, index, array) { /* ... */ }, thisArg)
Here, arr is an array.
filter() Parameters
The Array.filter() method can take three parameters that are:
- callbackFn – The callback function to execute on each array element; returns true if the element passes the callback function. Otherwise, returns false. The function can take the following arguments:
- element – The current element to be passed in the array.
- index – The index of the current element being passed in the array.
- array – The array on which filter() method is invoked.
- thisArg – The value to use as this when executing the callback function. By default, it is undefined and optional.
Return value
The filter() method returns a new array with all elements that match a specific criteria defined in a callback function. If no elements pass the test condition, the filter() method returns an empty array.
Filtering Array Elements that Meet Specific Criteria
Let us take an example in which we will filter all even numbers from an array of numbers. Then, we copy that even numbers into a new array.
Program code 2:
<script> const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; // Create a function to check even numbers. function checkEven(num) { if (num % 2 == 0) return true; else return false; } // Create a new array by filtering even numbers from the numbers array. const evenNumbers = numbers.filter(checkEven); document.write("Even numbers after filtering: " +evenNumbers); </script>
Output: Even numbers after filtering: 2,4,6,8,10
Let’s create the above program using arrow function and anonymous function.
Program code 3: Using arrow function
<script> const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; // Create an arrow function to check even numbers. let checkEven = num => (num % 2 == 0); // Create a new array by filtering even numbers from the numbers array. const evenNumbers = numbers.filter(checkEven); document.write("Even numbers after filtering: " +evenNumbers); </script>
Program code 4: Using anonymous function
<script> const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; // Create an anonymous function to check even numbers. let checkEven = function(num) { if(num % 2 == 0) return true; else return false; }; // Create a new array by filtering even numbers from the numbers array. const evenNumbers = numbers.filter(checkEven); document.write("Even numbers: " +evenNumbers); </script>
Find all Prime numbers from an Array of numbers
The following example code returns all prime numbers from an array of numbers:
Program code 5:
<script> const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; // Create a callback function to find prime numbers. function isPrime(num) { for (let i = 2; num > i; i++) { if (num % i == 0) { return false; } } return num > 1; } // Create a new array by filter prime numbers from the numbers array. const primeNumbers = numbers.filter(isPrime); document.write("Prime numbers: " +primeNumbers); </script>
Output: Prime numbers: 2,3,5,7
Searching in an Array
The following example code uses filter() method to filter array items based on search criteria.
Program code 6:
<script> let languages = ["C", "C++", "JavaScript", "Python", "Perl", "Swift", "PHP", "Java"]; // Create a function named searchElement. function searchElement(arr, query) { function condition(element) { // This statement converts array elements into lowercase. let lcElement = element.toLowerCase(); // This statement converts search query into lowercase. let lcQuery = query.toLowerCase(); // This statement returns the position of the first occurrence of an element in a string. let index = lcElement.indexOf(lcQuery) !== -1; return index; } return arr.filter(condition); } let newArr = searchElement(languages, "ja"); document.write(newArr, "<br>"); let newArr2 = searchElement(languages, "p"); document.write(newArr2); </script>
Output: JavaScript,Java JavaScript,Python,Perl,PHP
Here, we have used toLowerCase() method of JS String to convert both elements and query into lowercase.
Next, we have used indexOf() method of JS String to check that the query is present inside the element. This method returns the position of the first occurrence of the element in a string. It returns -1 if not found element. It is case sensitive.
Those array elements that do not pass this test condition are filtered out. We can also write the same callback function using arrow and anonymous functions.
Using arrow function: const searchElement = (arr, query) => { return arr.filter(element => element.toLowerCase().indexOf(query.toLowerCase()) !== -1) }
Using anonymous function: function searchElement(arr, query) { return arr.filter(function(el) { return el.toLowerCase().indexOf(query.toLowerCase()) !== -1 }) }
Try It Yourself
Program code 7:
<script> const nums = [150, 200, null, 130, 500, "Hundred", 600]; function checkNums(x) { return x > 150 && !Number.isNaN(x); } let filteredNumbers = nums.filter(checkNums); document.write(filteredNumbers); </script>
Program code 8:
<script> const values = [0, 1, "1", null, true, false, "JavaScript"]; function check(x) { return x == true; } let filteredValues = values.filter(check); document.write(filteredValues); </script>
In this tutorial, you have learned JavaScript Array filter() method with many example programs. Hope that you will have understood the basic concept of Array.filter() method and practiced all programs.
Thanks for reading!!!
Next ⇒ JavaScript array find() method⇐ Prev Next ⇒