Filtering Lists
Filtering lists is choosing only some items from an array before rendering them. The filter method keeps the items that pass a test and drops the rest.
Keeping the even numbers
The test keeps a number when the rest after dividing by two is zero.
const even = numbers.filter((n) => n % 2 === 0);Filter before map
Filter runs first and map runs on the kept items.
const even = numbers.filter((n) => n % 2 === 0);
return <ul>{even.map((n) => <li key={n}>{n}</li>)}</ul>;Filtering by a word
The test can check the start of a name.
const long = names.filter((name) => name.length > 4);Example
export default function App() {
const numbers = [1, 2, 3, 4, 5, 6];
const even = numbers.filter((n) => n % 2 === 0);
return (
<ul>
{even.map((n) => <li key={n}>{n}</li>)}
</ul>
);
}
Key points
- Filter builds a new array from the items that pass.
- The test is a small function that returns true or false.
- Filter runs before map in the code.
- The rendered list shows only the kept items.
In this example, the array holds the numbers one through six. The filter method keeps only the even numbers. The map method builds one list item for each kept number. The page shows only the even numbers.
Note
Filter leaves the first array unchanged.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does filter do before map in the example?