filter
Create a new array keeping only items that pass a test.
Syntax
const result = arr.filter(item => condition)filter() creates a new array containing only the items for which the callback returns true.
The test function
Return a Boolean from the callback: true keeps the item, false drops it.
Example
Loading editor…
Press Run to execute the code.
When to use it
- Show only in-stock products by filtering out items where the stock property is zero.
- Return only admin users from a list when building an admin-only notification distribution list.
- Filter a log array to keep only error-level entries before displaying them in an error panel.
More examples
Filter numbers above a threshold
Returns a new array containing only scores that meet the passing threshold of 60.
const scores = [45, 72, 88, 31, 95, 60];
const passing = scores.filter(s => s >= 60);
console.log(passing); // [72, 88, 95, 60]Filter objects by property
Filters the products array to keep only items where inStock is true.
const products = [
{ name: "Pen", inStock: true },
{ name: "Desk", inStock: false },
{ name: "Chair", inStock: true }
];
const available = products.filter(p => p.inStock);
console.log(available.map(p => p.name)); // ["Pen", "Chair"]Remove falsy values
Uses the Boolean constructor as the filter callback to remove all falsy values from an array.
const values = [0, "hello", null, 42, "", undefined, true];
const truthy = values.filter(Boolean);
console.log(truthy); // ["hello", 42, true]
Discussion