JavaScript Interview Question #42
How does filter() work in JavaScript?
Objects, Arrays & Core Data Handling Junior Beginner
Quick Interview Answer
filter returns a new array containing only the elements for which the callback returns a truthy value. It does not modify the original array.
Detailed Explanation
filter returns a new array containing only the elements for which the callback returns a truthy value. It does not modify the original array.
filter is useful for search results, permission filtering, status filtering, and other cases where a subset of a collection is required.
Code Example
const products = [
{ name: "A", active: true },
{ name: "B", active: false },
{ name: "C", active: true }
];
const activeProducts =
products.filter(p => p.active);
console.log(activeProducts);