Home >>JavaScript Array Reference >JavaScript Array filter() Method

JavaScript Array filter() Method

JavaScript Array filter() Method

JavaScript arr.filter() method is used to create a new array from a given array consisting of only those elements from the given array which satisfy a condition set by the argument function.

The filter() method creates an array filled with all array elements that pass a test (provided as a function).

Syntax:

var newArray = arr.filter(arg_function[, this_arg])

Parameter Values

Parameter Description
function(currentValue, index,arr) It Required, a function to be run in the array for each element.
Argument Description
currentValue It Required the value of the current element
index It is Optional and is used the array index of the current element
arr It is Optional and is used the array object the current element belongs to
thisValue It is Optional. A value passed to the function to be used as its "this" value. the value "undefined" will be passed as its "this" value, If this parameter is empty.

Browser Support

Method Chrome Edge Firefox Safari Opera
filter() Yes 9.0 1.5 Yes Yes

Here is an example of JavaScript array filter() Method:

<!DOCTYPE html>
<html>
<body>
<button onclick="myFilter()">Click me</button>
<p id="filter"></p>
<script>
var filter = [22, 28, 14, 35];
function checkAdult(age) {
  return age >= 18;
}
function myFilter() {
  document.getElementById("filter").innerHTML = filter.filter(checkAdult);
}
</script>
</body>
</html>
Output:

 

Example 2:

<!DOCTYPE html>
<html>
<body>
<script>
function filter1(element, index, array) {
  return element>=23;
}
document.writeln([18,35,16,45].filter(filter1));
</script>
</body>
</html>
Output:

No Sidebar ads