Lesson 34 - JavaScript Array Methods – filter()
The filter()
method creates a new array containing elements that pass a specific condition defined by a callback function.
Explanation
filter()
loops through an array and includes only elements that returntrue
from the callback function.- It does not modify the original array.
Syntax:
let filteredArray = array.filter(function(element, index, array) {
// return true to keep the element, false to exclude
});
element
: The current element being processed.index
(optional): The index of the current element.array
(optional): The arrayfilter
was called upon.
Example 1: Filtering Even Numbers
let numbers = [1, 2, 3, 4, 5, 6];
let evens = numbers.filter(num => num % 2 === 0);
console.log(evens); // Output: [2, 4, 6]
- Only even numbers are kept.
Example 2: Filtering Objects by Property
let users = [
{ name: 'Alice', age: 25 },
{ name: 'Bob', age: 17 },
{ name: 'Charlie', age: 30 }
];
let adults = users.filter(user => user.age >= 18);
console.log(adults);
// Output: [{ name: 'Alice', age: 25 }, { name: 'Charlie', age: 30 }]
- Filters users who are 18 or older.
Example 3: Removing Falsy Values
let mixedArray = [0, "Hello", false, "", 42, null, "JavaScript"];
let truthyValues = mixedArray.filter(Boolean);
console.log(truthyValues); // Output: ["Hello", 42, "JavaScript"]
- Removes falsy values like
0
,false
,""
, andnull
.
Try Your Hand
Steps:
-
Create a File:
- Name it
lesson34-filter.html
.
- Name it
-
Write the Code:
-
Copy the following code:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Lesson 34 - filter() Method</title> </head> <body> <h2>Even Numbers</h2> <ul id="evenList"></ul> <script> let numbers = [10, 15, 20, 25, 30, 35]; let evens = numbers.filter(num => num % 2 === 0); let list = document.getElementById("evenList"); evens.forEach(num => { let li = document.createElement("li"); li.textContent = num; list.appendChild(li); }); </script> </body> </html>
-
-
Save the File.
-
Open it in a Browser to See the Even Numbers.
Experiment
- Filter an array of names to include only names starting with the letter "A".
- Given an array of numbers, filter out all numbers less than 50.
- From an array of objects representing tasks, filter out only completed tasks.
Key Takeaways
filter()
returns a new array based on a true/false condition.- The original array remains unchanged.
- Useful for refining data sets.