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

Lesson 35: Combining array methods into processing pipelines

01Opening question

"Show the names of the three best-selling in-stock products, in capitals." Can one readable chain of array methods answer that?

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

Each method returns a new array, so the next method can be called on it.

const products = [
  { name: "lamp", sold: 40, inStock: true },
  { name: "rug", sold: 75, inStock: false },
  { name: "desk", sold: 60, inStock: true }
];
const top = products
  .filter((p) => p.inStock)
  .sort((a, b) => b.sold - a.sold)
  .map((p) => p.name.toUpperCase());
console.log(top);

03Objective and prerequisites

Learning objective: Chain filter, map, sort, slice and reduce into a processing pipeline, order the steps for correctness and efficiency, and debug a pipeline one step at a time.

You need: Lesson 32: map and transformations, Lesson 33: filter and selection, Lesson 34: reduce and aggregation

Skills practised: Functional array processing, Data pipelines.

04Explanation

Because filter, map and slice return arrays, you can chain them: list.filter(...).map(...). The output of one step is the input of the next.

Write one step per line, starting each line with the dot. The chain then reads like a recipe: keep these, sort them, take three, turn them into names.

Order matters. Filter first so later steps process fewer items; sort before slice when you want the top items; map to display values last.

reduce usually ends a chain because it returns a single value, not an array.

05Definitions

Method chaining
Calling a method on the result of the previous method call.
Pipeline
A sequence of steps where each step's output is the next step's input.
Intermediate result
The value produced partway through a pipeline.
Tap
A temporary step that logs a value without changing it, used for debugging.
Declarative code
Code that says what result you want rather than how to loop for it.

Open the full glossary

06Visual learning object

Data pipeline builder. Step through a pipeline and see the intermediate array after each method.

Loading the interactive object…

Open the full Data pipeline builder page with its guided experiment.

07Examples

ex-035-01Filter, then map Browser-executable JavaScript

Keep the paid orders, then turn them into labels.

const orders = [
  { id: 1, total: 20, paid: true },
  { id: 2, total: 50, paid: false },
  { id: 3, total: 35, paid: true }
];
const labels = orders
  .filter((o) => o.paid)
  .map((o) => `#${o.id}: $${o.total}`);
console.log(labels);
Sample input
None
Expected output
["#1: $20", "#3: $35"]
Common mistake
Putting map first, then filtering strings that no longer have a paid property.
Try this
Add a step that keeps totals above 25.
Source
examples/ex-035-01-filter-map.js (repository pending publication)

ex-035-02Top three Browser-executable JavaScript

Sort, slice, then map.

const players = [
  { name: "Ada", pts: 31 }, { name: "Bo", pts: 12 },
  { name: "Cy", pts: 44 }, { name: "Di", pts: 27 }
];
const podium = players
  .slice()
  .sort((a, b) => b.pts - a.pts)
  .slice(0, 3)
  .map((p, i) => `${i + 1}. ${p.name}`);
console.log(podium.join(" "));
Sample input
None
Expected output
1. Cy 2. Ada 3. Di
Common mistake
Slicing before sorting, which takes the first three players instead of the best three.
Try this
Show the points next to each name.
Source
examples/ex-035-02-top-n.js (repository pending publication)

ex-035-03Ending with reduce Browser-executable JavaScript

A pipeline can end with one summary value.

const lines = [
  { qty: 2, price: 5, taxable: true },
  { qty: 1, price: 20, taxable: false },
  { qty: 3, price: 4, taxable: true }
];
const taxableTotal = lines
  .filter((l) => l.taxable)
  .map((l) => l.qty * l.price)
  .reduce((sum, x) => sum + x, 0);
console.log(taxableTotal);
Sample input
None
Expected output
22
Common mistake
Forgetting the 0 initial value at the end of the chain.
Try this
Calculate the tax at 10% on that total.
Source
examples/ex-035-03-end-with-reduce.js (repository pending publication)

ex-035-04Named steps Browser-executable JavaScript

Small named functions make the pipeline read like requirements.

const isActive = (u) => u.active;
const byNewest = (a, b) => b.joined - a.joined;
const toName = (u) => u.name;
const users = [
  { name: "Ada", active: true, joined: 2021 },
  { name: "Bo", active: false, joined: 2024 },
  { name: "Cy", active: true, joined: 2023 }
];
console.log(users.filter(isActive).sort(byNewest).map(toName));
Sample input
None
Expected output
["Cy", "Ada"]
Common mistake
Writing all the logic inline until the chain is unreadable.
Try this
Add a step that keeps users who joined after 2022.
Source
examples/ex-035-04-named-steps.js (repository pending publication)

08Guided exercises

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

Sort before slicing

Fix the order of steps in a pipeline.

const sales = [
  { rep: "Ada", amount: 300 },
  { rep: "Bo", amount: 900 },
  { rep: "Cy", amount: 150 },
  { rep: "Di", amount: 700 }
];
const topTwo = sales
  .slice(0, 2)
  .sort((a, b) => b.amount - a.amount)
  .map((s) => s.rep);
console.log(topTwo);

Word statistics

Build a pipeline over text.

const text = "the quick brown fox jumps over the lazy dog";
// TODO: count the words longer than 3 letters and print them in capitals

Regional sales report

Combine several pipelines into a small report.

const sales = [
  { region: "North", product: "Lamp", units: 5, price: 30 },
  { region: "South", product: "Rug", units: 2, price: 120 },
  { region: "North", product: "Rug", units: 1, price: 120 },
  { region: "East", product: "Lamp", units: 8, price: 30 },
  { region: "South", product: "Lamp", units: 0, price: 30 }
];

09Prediction

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

const r = [5, 1, 4, 2]
  .filter((n) => n > 1)
  .map((n) => n * 10)
  .reduce((a, b) => a + b, 0);
console.log(r);

What is printed?

10Debugging investigation

The clearance total includes full-price items

The clearance report should total only items marked clearance, but it shows a total of 0.

const items = [
  { name: "Lamp", price: 30, clearance: false },
  { name: "Vase", price: 20, clearance: true },
  { name: "Rug", price: 15, clearance: true }
];
const total = items
  .map((i) => i.price)
  .filter((i) => i.clearance)
  .reduce((sum, p) => sum + p, 0);
console.log("Clearance total:", total);

More cases in the Debugging Detective Laboratory

11Practical scenario

Dashboard widgets from one dataset

An analytics dashboard builds every widget (top products, revenue by region, count of refunds) as a short pipeline over the same raw sales array. Each widget is one readable chain, and none of them changes the data the others use.

const s = [{ p: "A", r: 50 }, { p: "B", r: 80 }, { p: "C", r: 20 }];
console.log(s.slice().sort((a, b) => b.r - a.r).slice(0, 2).map((x) => x.p));

12Knowledge check

1. What is printed?

console.log([1, 2, 3, 4].filter((n) => n % 2 === 0).map((n) => n * n));
  • [4, 16]
  • [1, 4, 9, 16]
  • [2, 4]
  • 20

2. Why filter before map when possible?

  • It is required
  • Later steps then process fewer items, and the filter can still read the original properties
  • map cannot follow filter
  • It sorts the data

3. Why does the original list change order?

const top = list.sort(byScore).slice(0, 3);
  • filter mutates
  • sort is called on the original array
  • map mutates
  • slice mutates

4. Which method normally ends a chain with one value?

  • map
  • filter
  • reduce
  • slice

5. What is printed?

const r = [{ n: "A", q: 1 }, { n: "B", q: 5 }].filter((x) => x.q > 2).map((x) => x.n);
console.log(r);
  • ["B"]
  • ["A", "B"]
  • []
  • ["A"]

6. How would you debug a five-step chain that returns the wrong result?

  • Rewrite it as one reduce
  • Split it into named intermediate variables and log each
  • Remove steps until it works
  • Add more steps

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.

  • Sort before slicing: Prints Bo and Di; sales keeps its order
  • Word statistics: Prints the words and count; Uses filter and map
  • Regional sales report: Prints the report; revenueByRegion is correct; bestRegion works on other data
  • ex-035-01: output matches the documented expected output
  • ex-035-02: output matches the documented expected output
  • ex-035-03: output matches the documented expected output
  • ex-035-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-035-combining-array-methods-into-processing-pipelines/. Every example on this page is generated from those files.

The GitHub repository (https://github.com/lsvekis/JavaScript-Professional-Academy) has not been published yet, so these links will work once it is. Until then, use the ZIP download above.

15Summary and next steps

  • Chain array methods: each returns the input of the next.
  • Filter early, sort before slice, map for display, reduce to finish.
  • Copy before sorting shared data.
  • Name steps and inspect intermediate results to debug.

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 array method pipelines
Context: I am learning array method pipelines in JavaScript.
Task: Explain method chaining with filter, sort, slice, map and reduce using a sales dashboard 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 array method pipelines drill
Context: I have practised array method pipelines.
Task: Show me five pipelines and ask what each returns, with one where step order changes the result.
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 array method pipelines bug
Context: My pipeline returns the wrong items or changes my original array.
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 array method pipelines practice
Context: I finished the array method pipelines exercises.
Task: Create three pipeline exercises over sales and student data.
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 array method pipelines review
Context: Here is my code that uses array method pipelines.
Task: Review my pipelines for step order, mutation and readability, and suggest named steps.
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.