How do you filter an array in JavaScript?
Table of Contents
Introduction
Filtering an array is a common operation in JavaScript, often used to create a new array based on a specific condition. The filter()
method in JavaScript allows you to iterate over an array and return a new array containing elements that pass the condition (also called a test). Let’s dive into how the filter()
method works with examples for numbers, strings, and objects.
Filtering Arrays in JavaScript
1. Syntax of the filter()
Method
The filter()
method takes a callback function that runs for each element of the array. If the callback returns true
, the element is included in the new filtered array.
element
: The current element being processed.condition
: A condition or test that each element must pass to be included in the new array.
2. Filtering an Array of Numbers
Let's start with filtering an array of numbers to only include numbers greater than a specific value.
- The filter returns a new array with numbers greater than
30
.
3. Filtering an Array of Strings
You can filter an array of strings based on a specific string pattern or condition.
- The filter checks if the string contains the letter
'a'
, and includes it if the condition is true.
4. Filtering an Array of Objects
Filtering an array of objects can be done by checking a property within each object.
- The filter returns a new array containing only people whose age is greater than 30.
Practical Examples of Array Filtering
1. Filtering Even Numbers
To filter out even numbers from an array, you can use the modulo operator (%
).
- The filter checks if the number is divisible by 2.
2. Filtering by String Length
You can filter strings in an array by their length.
- The filter checks if the string length is greater than 4.
Conclusion
The filter()
method in JavaScript is a powerful way to filter arrays based on a condition. It can be used to filter numbers, strings, or even objects based on a specific test. Whether you're working with simple arrays or complex data structures, filtering allows you to extract exactly what you need from your data efficiently.