Filtering and sorting
- React course
- Beginner
- Lesson 30/84
- 4 min
Learn to render an array after filtering and sorting it.
Filtering and sorting
Before drawing the list you filter with filter and sort with sort. filter returns a new array; the original is untouched. sort mutates in place.
Example: {items.filter(i => i.active).map(...)}. Only active items survive, then map draws them.
Order matters: filter first, then sort, then map. That way you skip needless sorting.
Original stays intact
filter always produces a new array; it never mutates. sort mutates in place, so taking a copy with [...items] first is safe.
In React you never mutate state directly; copying before sort is a good habit. We will see state later; for now know the copy trick.
map always produces a new array; no extra copy is needed.
Practice FilteredList component
Complete the skeleton. Write a FilteredList component. The items array has id, name and active on each item. Use filter to keep only items where active is true, then map them into <li key={item.id}>{item.name}</li>. Export it.
Starter code
// Define FilteredList hereSample solution
function FilteredList() {
const items = [{ id: 1, name: "Alex", active: true }, { id: 2, name: "Sam", active: false }];
return <ul>{items.filter(i => i.active).map(item => <li key={item.id}>{item.name}</li>)}</ul>;
}
export default FilteredList;Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Filtering and sorting: match the terms
| Term | Meaning |
|---|---|
filter |
Keeps some items |
sort |
Orders items |
reverse |
Flips order |
map |
Transforms items |
2 What does [3,1,2].sort() return?
sort returns an array.- The sorted array (same reference) Correct answer
- [3,1,2]
- undefined
- [1,2,3]
Explanation: sort returns the sorted array reference.
3 Filtering and sorting: fill in the missing part
{items.filter(____).map(i => <li key={i.id}>{i.name}</li>)}
{items.filter(i => i.active).map(i => <li key={i.id}>{i.name}</li>)}
Explanation: Only active items get drawn by map.