JavaScript Array filter()

Posted by

Method

Introduction to JavaScript Array filter() Method

The Array.filter() method in JavaScript is used to create a new array with all elements that pass the test implemented by the provided function. It calls a provided callback function once for each element in an array, and constructs a new array of all the values for which callback returns a value that coerces to true. The filter() method is used to iterate through an array and filter out elements that do not pass a certain criteria.

Syntax

The syntax for the filter() method is as follows:

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

arr.filter(callback(element[, index[, array]])[, thisArg]);

[/dm_code_snippet]

The filter() method takes in a callback function as its argument, and an optional thisArg argument. The callback function is called for every element in the array. The callback function has three parameters:

  • element: The array element
  • index (optional): The index of the array element
  • array (optional): The array object the current element belongs to

The thisArg argument is an optional argument that defines what the this keyword inside the callback function refers to. If this argument is not provided, the this keyword inside the callback function refers to the global object.

Example

Let’s look at an example of how to use the filter() method. We have an array of numbers, and we want to filter out all numbers that are greater than 5:

[dm_code_snippet background=”yes” background-mobile=”yes” slim=”no” line-numbers=”no” bg-color=”#abb8c3″ theme=”dark” language=”php” wrapped=”no” height=”” copy-text=”Copy Code” copy-confirmed=”Copied”]

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

const filteredNumbers = numbers.filter(num => num > 5);

console.log(filteredNumbers); // Output: [6, 7, 8, 9, 10]

[/dm_code_snippet]

In this example, we are using the arrow function syntax to define our callback function. Inside the callback function, we are checking if the element is greater than 5. If it is, the element is added to the filteredNumbers array, otherwise it is not added. The filter() method then returns a new array with all the elements that passed the test. In our case, that is all the numbers greater than 5.

Conclusion

The Array.filter() method in JavaScript is a powerful tool to filter out elements in an array that do not pass a certain criteria. The callback function can be used to define the criteria, and a new array is returned with all elements that pass the test. This method can be used to filter out elements in large datasets, or to select elements from an array based on certain criteria.