Skip to content

JavaScript array filter Method | Example code

  • by

JavaScript array filter method is to create a new array and filled with all array elements which passed a condition or test. It will return a new array with the elements that pass the condition. If no elements pass the test, an empty array will be returned.

Note: Filter method is not changed a given array.

Syntax

array.filter(function(currentValue, index, arr), thisValue)

Parameter Values

  • function: To test each element of the array.
    • currentValue: current element value
    • index: Optional index of current element.
    • arr: Optional array object.
  • thisValue: use as this when executing callback.

Example of JavaScript array filter Method

Let’s try an example where get all the values in the ages an array that is 18 or over.

<html>  
<head>  
    <title>Sample Code</title>  
    <script type="text/javascript">  
  	var ages = [12, 28, 16, 50, 10];

	function checkAdult(age) {
  		return age >= 18;
	}
  		alert(ages.filter(checkAdult));
    </script>  
</head>  
</html>

Output:

JavaScript array filter Method

Do comment if you have any doubts and suggestion on this tutorial.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading