Tutorialspoint.dev

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:

<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>

Output:

[112,52,944]

Program 2:

<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>

Output:

[98,944]


This article is attributed to GeeksforGeeks.org

leave a comment

code

0 Comments

load comments

Subscribe to Our Newsletter