**filter()** returns a new array containing only elements for which the callback returns a truthy value. It never mutates the original. Use it to select subsets of data. Combine with **map()** for transform-then-select pipelines.
1Understanding Array.filter()
filter() returns a new array containing only elements for which the callback returns a truthy value. It never mutates the original. Use it to select subsets of data. Combine with map() for transform-then-select pipelines.
Boolean can be used as the filter callback to remove all falsy values: arr.filter(Boolean) removes null, undefined, 0, '', false, NaN.
const people = [
{ name: 'Alice', age: 30, active: true },
{ name: 'Bob', age: 17, active: true },
{ name: 'Carol', age: 25, active: false },
];
const activeAdults = people
.filter(p => p.active && p.age >= 18)
.map(p => p.name);
console.log(activeAdults); // ['Alice']2Practical Example
Here is a real-world application of Array.filter() showing how it is used in production JavaScript code.
// Remove falsy values
const mixed = [1, null, 2, undefined, 3, '', 4, false, 5];
const clean = mixed.filter(Boolean);
console.log(clean); // [1, 2, 3, 4, 5]3Best Practices
Follow these guidelines when working with Array.filter():
1. Use filter(Boolean) to remove falsy values
2. Chain filter().map() for select-then-transform
3. Use find() if you only need the first matching element
Tip: Boolean can be used as the filter callback to remove all falsy values: arr.filter(Boolean) removes null, undefined, 0, '', false, NaN.
const people = [
{ name: 'Alice', age: 30, active: true },
{ name: 'Bob', age: 17, active: true },
{ name: 'Carol', age: 25, active: false },
];
const activeAdults = people
.filter(p => p.active && p.age >= 18)
.map(p => p.name);
console.log(activeAdults); // ['Alice']