JavaScript AcademyProfessional Engineering
Level 2 · Core DevelopmentModule 7: Functional Array ProcessingLesson 33 of 150About 40 minutes

Lesson 33: filter and selection

01Opening question

A shop has 2,000 products and a customer ticks "in stock" and "under $50". How does the list shrink to just the matches?

Keep the question in mind. By the end of the lesson you will be able to answer it, and prove it with working code.

02Start with working code

filter keeps the elements for which the callback returns true.

const prices = [12, 75, 30, 120, 8];
const affordable = prices.filter((p) => p < 50);
console.log(affordable);
console.log(prices.some((p) => p > 100), prices.every((p) => p > 5));

03Objective and prerequisites

Learning objective: Use filter to keep the elements that pass a test, write clear predicate functions, combine conditions, and use some and every to answer yes/no questions about a list.

You need: Lesson 32: map and transformations, Lesson 12: Logical operators

Skills practised: Functional array processing, Selecting with filter.

04Explanation

list.filter(test) returns a new array containing only the elements for which test returns true. The original array is unchanged.

The test function is called a predicate: it answers a yes/no question about one element, such as (p) => p.inStock.

Combine conditions inside the predicate with && and ||: (p) => p.inStock && p.price < 50.

some(test) is true if at least one element passes; every(test) is true if all of them do. Both stop as soon as they know the answer.

05Definitions

filter
Returns a new array with only the elements that pass a test.
Predicate
A function that returns true or false for one value.
some
True when at least one element passes the test.
every
True when all elements pass the test.
Falsy
A value treated as false: 0, "", null, undefined, NaN or false.

Open the full glossary

06Visual learning object

Filter selection visualizer. See which elements the predicate keeps and which it drops, and what some and every answer.

Loading the interactive object…

Open the full Filter selection visualizer page with its guided experiment.

07Examples

ex-033-01Keep what passes Browser-executable JavaScript

filter returns a new, shorter (or equal) array.

const temps = [14, 22, 27, 19, 31];
const warm = temps.filter((t) => t >= 22);
console.log(warm, warm.length);
console.log(temps.length);
Sample input
None
Expected output
[22, 27, 31] 3 5
Common mistake
Expecting filter to return true or false.
Try this
Keep the temperatures below 20.
Source
examples/ex-033-01-filter-numbers.js

ex-033-02Filtering objects with two conditions Browser-executable JavaScript

Combine conditions inside the predicate.

const products = [
  { name: "Lamp", price: 30, inStock: true },
  { name: "Rug", price: 80, inStock: true },
  { name: "Vase", price: 25, inStock: false }
];
const matches = products.filter((p) => p.inStock && p.price < 50);
console.log(matches.map((p) => p.name));
Sample input
None
Expected output
["Lamp"]
Common mistake
Writing p.inStock = true, which assigns instead of comparing.
Try this
Show items under $50 OR on sale.
Source
examples/ex-033-02-filter-objects.js

ex-033-03Named predicates Browser-executable JavaScript

Small named tests make filters readable.

const isPaid = (o) => o.status === "paid";
const isLarge = (o) => o.total >= 100;
const orders = [
  { id: 1, status: "paid", total: 120 },
  { id: 2, status: "open", total: 300 },
  { id: 3, status: "paid", total: 40 }
];
console.log(orders.filter(isPaid).length);
console.log(orders.filter(isPaid).filter(isLarge).map((o) => o.id));
Sample input
None
Expected output
2 [1]
Common mistake
Calling the predicate: filter(isPaid()) instead of filter(isPaid).
Try this
Write isOpen and count open orders.
Source
examples/ex-033-03-named-predicates.js

ex-033-04some and every Browser-executable JavaScript

Yes/no questions about the whole list.

const ages = [19, 24, 17, 31];
console.log(ages.some((a) => a < 18));
console.log(ages.every((a) => a >= 18));
console.log([].every((a) => a > 100), [].some((a) => a > 100));
Sample input
None
Expected output
true false true false
Common mistake
Using filter(...).length > 0 where some is clearer.
Try this
Check whether every age is under 65.
Source
examples/ex-033-04-some-every.js

08Guided exercises

Three exercises: explore and modify, complete the implementation, then build independently. Tests check behaviour, so any correct solution passes.

Compare, do not assign

Fix a predicate that assigns instead of comparing.

const tickets = [
  { id: 1, status: "open" },
  { id: 2, status: "closed" },
  { id: 3, status: "open" }
];
const open = tickets.filter((t) => t.status = "open");
console.log(open.length, tickets[1].status);

Search box

Filter by text, ignoring case.

const books = ["Dune", "Emma", "Middlemarch", "The Hobbit", "Moby Dick"];
const query = "m";
// TODO: keep books whose title contains the query, ignoring case

Rental search filters

Combine named predicates and check the results with some and every.

const rentals = [
  { id: "A", beds: 2, price: 1400, pets: true },
  { id: "B", beds: 1, price: 1100, pets: false },
  { id: "C", beds: 3, price: 2100, pets: true },
  { id: "D", beds: 2, price: 1650, pets: true }
];

09Prediction

Commit to an answer first, then run the real code to compare.

const v = [0, 1, "", "a", null, 2];
console.log(v.filter(Boolean));

What is printed?

10Debugging investigation

Free items disappear from the order

A promotion adds a free tote bag (price 0), but it vanishes from the order list.

const lines = [
  { name: "Mug", price: 8 },
  { name: "Tote", price: 0 },
  { name: "Tea", price: 5 },
  { name: "Unknown", price: undefined }
];
const valid = lines.filter((l) => l.price);
console.log("Lines:", valid.map((l) => l.name).join(", "));

More cases in the Debugging Detective Laboratory

11Practical scenario

Product search filters

Each tick box on a shop's filter panel is one predicate. The visible list is the catalogue filtered by all active predicates, and the original catalogue is never changed, so unticking a box restores results instantly.

const items = [{ p: 30, s: true }, { p: 80, s: true }];
const active = [(x) => x.s, (x) => x.p < 50];
console.log(items.filter((x) => active.every((f) => f(x))).length);

12Knowledge check

1. What is printed?

console.log([1, 2, 3, 4].filter((n) => n % 2 === 0));
  • [2, 4]
  • [1, 3]
  • [true, false]
  • 2

2. What does a predicate return?

  • A new array
  • true or false (truthy/falsy)
  • An index
  • Nothing

3. What is printed?

console.log([1, 8, 3].some((n) => n > 5));
  • true
  • false

4. What is printed?

console.log([].every((n) => n > 5));
  • true
  • false

5. Why are zero-quantity lines kept AND valid 0 prices removed?

const prices = [0, 5, null, 9].filter(Boolean);
  • filter(Boolean) removes every 0
  • Boolean is not a function
  • filter mutates
  • Nothing is wrong

6. You only need to know whether any order is overdue. Which is best?

  • orders.filter(isOverdue).length > 0
  • orders.some(isOverdue)
  • orders.map(isOverdue)
  • orders.every(isOverdue)

13Solutions and tests

Each exercise's solution appears in the exercise once you have run its tests. Solutions are one possible answer: the tests accept any implementation with the same behaviour.

Automated acceptance tests for this lesson

These are the same checks the exercises run. They are visible on purpose: client-side tests help you learn and are not secret.

  • Compare, do not assign: Prints 2 closed
  • Search box: Prints the matches; Uses filter
  • Rental search filters: Prints matches and checks; hasBeds returns a predicate; underBudget is strict
  • ex-033-01: output matches the documented expected output
  • ex-033-02: output matches the documented expected output
  • ex-033-03: output matches the documented expected output
  • ex-033-04: output matches the documented expected output

Download the whole lesson folder (examples, exercises, solutions, tests) as ZIP

14Source files

The lesson lives in the companion repository at curriculum/level-02-core-development/module-07-functional-array-processing/lesson-033-filter-and-selection/. Every example on this page is generated from those files.

These links open the files in the GitHub repository (https://github.com/lsvekis/JavaScript-Professional-Engineering-Academy). You can also use the ZIP download above.

15Summary and next steps

  • filter keeps the elements whose predicate returns true.
  • Combine conditions with && and || in the predicate.
  • some: at least one; every: all of them.
  • Named predicates make filters readable and testable.

16AI learning prompts

Copy a prompt into the AI assistant of your choice. Then verify what it says by running code here. No AI service is connected to this page.

Concept explanation filter, some and every
Context: I am learning filter, some and every in JavaScript.
Task: Explain filter, predicates, some and every with a product search example.
Constraints: Beginner-friendly language, short runnable examples, no libraries.
Expected behaviour: I can explain the idea in my own words and predict small programs.
Testing: Finish with three quick questions for me to answer.
Code prediction filter, some and every drill
Context: I have practised filter, some and every.
Task: Give me six filter, some and every calls and ask for the results, including empty arrays.
Constraints: Wait for my answer before revealing each result.
Expected behaviour: Each question has exactly one correct output.
Testing: Explain any I miss with a step-by-step trace.
Debugging filter, some and every bug
Context: My filter keeps every item and also changes my data.
Task: Help me find the cause with questions instead of giving me the fix.
Constraints: Do not rewrite my program.
Expected behaviour: I locate and fix the bug myself.
Testing: Suggest the console.log lines that would reveal the problem.
Exercise generation filter, some and every practice
Context: I finished the filter, some and every exercises.
Task: Create three filtering exercises with combined conditions.
Constraints: Fictional data and exact expected output.
Expected behaviour: Each exercise has tests I can run.
Testing: Put the solutions in a separate hidden section.
Code review filter, some and every review
Context: Here is my code that uses filter, some and every.
Task: Review my filters and suggest named predicates where conditions are hard to read.
Constraints: Explain each suggestion briefly and keep behaviour identical.
Expected behaviour: The code is clearer and has no hidden mutation or edge-case bug.
Testing: List the changes in order of importance.