00:00
03:45
About Lesson
JavaScript Array filter()
Method
-
Purpose: Creates a new array containing only the elements of the original array that pass a specified test condition.
-
Syntax:
JavaScriptconst newArray = array.filter(callback(element, index, array))
callback
: A function that takes three arguments:element
: The current element being processed in the array.index
: The index of the current element in the array.array
: The original array.
- The
callback
function should returntrue
for elements to be included in the new array, andfalse
for elements to be excluded.
-
Example:
const numbers = [1, 2, 3, 4, 5]; const evenNumbers = numbers.filter(number => number % 2 === 0); console.log(evenNumbers); // Output: [2, 4] 1
* **Key Points:**
- The `filter()` method does not modify the original array. It creates a new array containing the filtered elements.
- The `filter()` method can be used to extract specific elements from an array based on various criteria.
- You can use arrow functions concisely within the `filter()` method.
**Common Use Cases:**
* **Filtering data based on specific conditions:**
- Filtering out invalid entries from a form.
- Selecting items from a list that match a search query.
- Extracting data that falls within a certain range.
* **Data cleaning and transformation:**
- Removing duplicates from an array.
- Filtering out unwanted elements before further processing.
The `filter()` method is a powerful tool for working with arrays in JavaScript, providing a concise and efficient way to extract specific elements based on your needs.