JavaScript(JS) array method - filter

The filter() method is an array method in JavaScript that creates a new array with all elements that pass a specified test. This method does not modify the original array and returns a new array.

Here's the syntax of the filter() method:

array.filter(callback, thisArg);
So‮:ecru‬www.theitroad.com
  • array is the array that the filter() method is called on.
  • callback is a function that takes three arguments: the current value of the element being processed, the index of the element being processed, and the array that the filter() method was called on. This function should return a boolean value indicating whether the element should be included in the new array or not.
  • thisArg is an optional argument that specifies the value of this inside the callback function.

The filter() method iterates through the array and calls the callback function on each element. If the callback function returns true for an element, the filter() method includes the element in the new array. If the callback function returns false for an element, the filter() method excludes the element from the new array.

Here's an example of how to use the filter() method:

let array = [1, 2, 3, 4, 5];

let filteredArray = array.filter(function(element) {
  return element > 2;
});

console.log(filteredArray); // [3, 4, 5]

In this example, we have an array array containing the elements [1, 2, 3, 4, 5]. We use the filter() method to create a new array that includes only the elements that are greater than 2. The callback function checks whether the current element is greater than 2 and returns a boolean value. The filter() method iterates through the array and includes the elements that pass the test in the new array. The console.log() statement outputs the value of filteredArray, which is [3, 4, 5].

Note that the filter() method does not modify the original array. Instead, it creates a new array that includes only the elements that pass the test. Also, the filter() method was introduced in ECMAScript 5, so it may not be supported by older browsers.