JavaScript | Array filter()

arr.filter() function 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 syntax of the given function is as follows:

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

Here arr is the original given array.

Argument
The argument to this function is another function that defines the condition to be checked for each element of the array. This arg_function itself takes three arguments:

  • array
  • This is the array on which the .filter() function was called.

  • index
  • This is the index of the current element being processed by the function.

  • element
  • This is the current element being processed by the function.

Another argument this_arg is used to tell the function to use this value when executing argument function.

Return value
This function returns a new array consisting of only those elements that satisfied the condition of the arg_function.

Examples for the above function is as follows:

Example 1:

function isPositive(value) {
  return value > 0;
}

var filtered = [112, 52, 0, -1, 944].filter(isPositive);
print(filtered);

Output:

[112,52,944]

In this example the function filter() creates a new array consisting of only those elements that satisfy the condition checked by isPositive() function.

Example 2:

function isEven(value) {
  return value % 2 == 0;
}

var filtered = [11, 98, 31, 23, 944].filter(isEven);
print(filtered);

Output:

[98,944]

In this example the function filter() creates a new array consisting of only those elements that satisfy the condition checked by isPositive() function.

Codes for the above function is as follows:

Program 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

<script>
// JavaScript to illustrate findIndex() function
function isPositive(value) {
  return value > 0;
}
  
function func() {
    var filtered = [112, 52, 0, -1, 944].filter(isPositive);
    document.write(filtered);
}
func();
</script>

chevron_right


Output:

[112,52,944]

Program 2:

filter_none

edit
close

play_arrow

link
brightness_4
code

<script>
// JavaScript to illustrate findIndex() function
function isEven(value) {
  return value%2 == 0;
}
  
function func() {
    var filtered = [11, 98, 31, 23, 944].filter(isEven);
    document.write(filtered);
}
func();
</script>

chevron_right


Output:

[98,944]


My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.