Collect All Matching Items from a List
Scenario
Collect all scores >= 60 from scores = [45, 72, 60, 58].
- 1Start: passed = [] -> inspect 45 (45 >= 60 is false)
- 2Inspect 72 (72 >= 60 is true)
- 3Inspect 60 (60 >= 60 is true)
- 4Inspect 58 (58 >= 60 is false) -> return passed
Try it yourself
Step through each score and watch the new result list grow in original order.
| Case | State after the step |
|---|---|
| Start: passed = [] -> inspect 45 (45 >= 60 is false) | — |
| Inspect 72 (72 >= 60 is true) | — |
| Inspect 60 (60 >= 60 is true) | — |
| Inspect 58 (58 >= 60 is false) -> return passed | — |
Reveal the explanation
- Start: passed = [] -> inspect 45 (45 >= 60 is false)
Skip 45. passed stays [].
- Inspect 72 (72 >= 60 is true)
Append 72. passed becomes [72].
- Inspect 60 (60 >= 60 is true)
Append 60. passed becomes [72, 60].
- Inspect 58 (58 >= 60 is false) -> return passed
Skip 58. Final result is [72, 60] while original scores stays unchanged.
Building a new result list preserves original order and keeps the caller’s input list intact for other checks.
Download shared test cases
Your turn
Trace filtering freeSeats > 0 on rooms = [0, 3, 0, 1] and state the final collected list.
Common mistake Overwriting the result list with [item] on every match instead of appending.
Check your work
Result is [3, 1]; original [0, 3, 0, 1] is untouched.
Quick check
This browser could not save your progress. Changes last until you leave the page.