Problem Statement
What does the filter method return?
Explanation
The filter method creates a new array containing only elements that pass a test function.
It returns a new array that may be shorter than the original. If no elements pass, it returns an empty array.
The test function should return true to keep the element, false to exclude it.
Filter does not modify the original array.
It is commonly used to remove unwanted elements or select specific items.
Code Solution
SolutionRead Only
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// Filter even numbers
const evens = numbers.filter(num => num % 2 === 0);
console.log(evens); // [2, 4, 6, 8, 10]
// Filter by condition
const greaterThanFive = numbers.filter(num => num > 5);
console.log(greaterThanFive); // [6, 7, 8, 9, 10]
// Filter objects
const users = [
{ name: 'John', age: 17 },
{ name: 'Jane', age: 25 },
{ name: 'Bob', age: 30 }
];
const adults = users.filter(user => user.age >= 18);
console.log(adults); // [{name: 'Jane', age: 25}, {name: 'Bob', age: 30}]
// Remove falsy values
const mixed = [0, 1, false, 2, '', 3, null, 4, undefined, 5];
const truthy = mixed.filter(Boolean);
console.log(truthy); // [1, 2, 3, 4, 5]
// No matches returns empty array
const none = numbers.filter(num => num > 100);
console.log(none); // []