Arrays
array.filter()
Builds a new array from only the items that pass a check.
Why it exists
"Show only…" is one of the most common requests of data: only unread emails, only products in stock, only today's tasks. You can do it with a loop, if and push, but filter says the same thing in one line, and it's immediately clear what is happening — selection. Most importantly, filter leaves the original array alone: the full list stays intact, and the filter can be removed.
Where it's used
- Shop filters: price, size, "in stock".
- Searching a list:
contacts.filter((c) => c.name.includes(query)). - Removing an item without changing the array:
todos.filter((t) => t.id !== id). - Selecting before transforming:
filter(…).map(…)— as in the "Names of adults" challenge.
Syntax
const result = array.filter((item) => condition);Examples
const nums = [5, 12, 8, 1];
const big = nums.filter((n) => n > 6);
big; // → [12, 8]
nums; // → [5, 12, 8, 1] — the original is unchangedconst todos = [
{ id: 1, title: "Buy bread", done: true },
{ id: 2, title: "Call mum", done: false },
];
todos.filter((t) => !t.done).length; // → 1const todos = [{ id: 1 }, { id: 2 }, { id: 3 }];
todos.filter((t) => t.id !== 2); // → [{ id: 1 }, { id: 3 }]const words = ["cat", "", "dog", ""];
words.filter((w) => w !== ""); // → ["cat", "dog"]Results after // → aren't just written down — an automatic check runs and verifies them before every site update.
Why it works this way
filter walks the array itself and calls your callback for each item. If the callback returns a truthy value, the item goes into the new array; if falsy, it doesn't. The order is kept.
The callback receives three arguments: the item, its index and the whole array. Usually you only need the first.
The result is always a new array, even if every item passed or none did (then it's []). The original array isn't changed, and the objects inside aren't copied: the new array holds references to the same objects.
In essence, filter is a for...of loop with if and push, tucked inside a method.
Traps
How it differs from…
array.map()map changes every item and keeps the length;
filterkeeps items as they are but can make the array shorter. They're often chained: select first, then transform.for...ofloopA loop is for when you're searching and want to stop at the first match, or doing several things at once.
filteralways walks the whole array.
When to pick something else
Practice
Lessons where this appears
- A page address from a titleLab · Chapter 7 · Regular expressions
- The conveyor at the fish factoryTale · Chapter 10 · map, filter, reduce
- Why map and not a loop?Why? · Chapter 10 · map, filter, reduce
- A shift on the conveyorWorkshop · Chapter 10 · map, filter, reduce
- Names of adultsLab · Chapter 10 · map, filter, reduce
- A cart classLab · Chapter 14 · this and classes