filter() creates a new array containing only the items for which your callback returns a truthy value. The original is unchanged.
const numbers = [1, 2, 3, 4, 5, 6];
const evens = numbers.filter(n => n % 2 === 0);
console.log(evens); // → [2, 4, 6]
console.log(numbers); // → [1, 2, 3, 4, 5, 6]
The result can be shorter than the original, or even empty.
Filtering objects
const products = [
{ name: "Notebook", price: 4, inStock: true },
{ name: "Laptop", price: 900, inStock: true },
{ name: "Pen", price: 1.5, inStock: false }
];
const affordable = products.filter(p => p.price < 100 && p.inStock);
console.log(affordable.map(p => p.name)); // → ["Notebook"]
Removing an item
filter is the usual way to remove an item without mutating the array.
const tasks = [
{ id: 1, text: "Wash up" },
{ id: 2, text: "Study" }
];
const withoutFirst = tasks.filter(task => task.id !== 1);
console.log(withoutFirst); // → [{ id: 2, text: Study }]
Removing empty values
const input = ["a", "", "b", null, "c", undefined];
console.log(input.filter(Boolean)); // → ["a", "b", "c"]
Boolean is used directly as the callback: it returns false for every falsy value.
Chaining with map
Because both return arrays, you can chain them.
const orders = [
{ id: 1, total: 20, paid: true },
{ id: 2, total: 50, paid: false },
{ id: 3, total: 35, paid: true }
];
const paidTotals = orders
.filter(order => order.paid)
.map(order => order.total);
console.log(paidTotals); // → [20, 35]
Read it top to bottom: keep the paid orders, then take their totals.
A live filter
<input id="q" placeholder="Filter fruit">
<ul id="out"></ul>
<script>
const fruit = ["apple", "apricot", "banana", "cherry"];
const out = document.querySelector("#out");
function show(term) {
out.innerHTML = "";
for (const f of fruit.filter(x => x.includes(term.toLowerCase()))) {
const li = document.createElement("li");
li.textContent = f;
out.append(li);
}
}
document.querySelector("#q").addEventListener("input", e => show(e.target.value));
show("");
</script>
filter, find, or some?
filter returns all matches (an array). find returns the first match. some returns true or false.