JavaScript filter() Method
filter() creates a new array containing only the elements that pass a test you define. The original array is not changed.
Syntax
const result = array.filter((element, index, array) => {
return /* true to keep, false to exclude */;
});
Your callback should return true to keep an element, or false (or any falsy value) to exclude it.
For loop vs filter()
Here is the same task written two ways. Finding everyone over 18:
// Using a for loop
const ages = [15, 6, 9, 20, 25, 14, 30];
const olderThan18 = [];
for (let i = 0; i < ages.length; i++) {
if (ages[i] > 18) {
olderThan18.push(ages[i]);
}
}
console.log(olderThan18); // [20, 25, 30]
// Using filter()
const ages = [15, 6, 9, 20, 25, 14, 30];
const olderThan18 = ages.filter(age => age > 18);
console.log(olderThan18); // [20, 25, 30]
filter() is more concise and reads like English: “filter ages where age is over 18.”
Filtering objects by a property
const users = [
{ name: 'Anna', active: true },
{ name: 'Joe', active: false },
{ name: 'Mira', active: true },
];
const activeUsers = users.filter(user => user.active);
console.log(activeUsers);
// [{ name: 'Anna', active: true }, { name: 'Mira', active: true }]
Removing a specific item
filter() is the standard way to remove an item from an array without mutating it. This pattern is common when managing state in React:
const items = [1, 2, 3, 4, 5];
const withoutThree = items.filter(item => item !== 3);
console.log(withoutThree); // [1, 2, 4, 5]
console.log(items); // [1, 2, 3, 4, 5] (unchanged)
Chaining filter() with map()
Because both methods return arrays, you can chain them:
const prices = [5, 120, 3, 85, 40];
const discounted = prices
.filter(price => price >= 50) // keep only prices 50 and above
.map(price => price * 0.9); // apply 10% discount
console.log(discounted); // [108, 76.5]
Common mistakes
Forgetting to return a value. If your callback does not explicitly return anything, it returns undefined, which is falsy. Nothing will pass the filter.
// Wrong: returns undefined, so nothing passes
const result = [1, 2, 3].filter(n => { n > 1; });
console.log(result); // []
// Correct
const result = [1, 2, 3].filter(n => n > 1);
console.log(result); // [2, 3]
Mutating the original array inside the callback. filter() is meant to be a pure operation. Changing the source array inside the callback leads to unpredictable results.