← Fundamentals
Fundamentals

Map, filter, and reduce

How do you transform a collection without writing the loop?

Express transformation, selection and accumulation as distinct operations on a collection.

Outcome

Rewrite a loop as map, filter or a fold, say what each keeps, choose where filter goes, give a fold a start value that is right for an empty collection and the right type, and predict when the callbacks run.

Terminology (5)Terms used in this lesson

Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.

map
Applies a function to every element and gives one result per element.
filter
Keeps the elements for which a test returns true, in order.
Fold (reduce)
Combines a collection into one value by repeatedly applying a function to an accumulator and the next element.
Start value
The accumulator a fold begins with; it is also the answer for an empty collection.
Lazy
Describes a pipeline that does no work until something asks for its results.

Three operations with different roles

Map transforms each item into one result. Filter keeps items satisfying a predicate. A fold or reduce combines items into an accumulator. For example, a report might convert measurements, select readings that meet a threshold and accumulate a total.

The order determines which values each step sees. The consumer also determines how much work is requested: TypeScript array methods materialize arrays, Rust iterator adapters wait for consumption, and C++ offers both output-writing algorithms and lazy views. Choose the accumulation operation, its starting value and its result type together.

01Mapping

map makes one result for every element

A shop report shows a 50-cent handling charge on each unit price, selects products whose original price is at least $5, and totals order lines. The selection rule uses the listed price before the charge. Moving the test changes which products appear.

The display adds a 50-cent handling charge to each unit price. Prices are whole cents. Predict the displayed prices and their count.

main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
fn main() {
    let unitCents = [600, 475, 1200, 300];
    let display_cents: Vec<i32> = unitCents.iter().map(|cents| cents + 50).collect();

    let shown: Vec<String> = display_cents
        .iter()
        .map(|cents| cents.to_string())
        .collect();

    println!("{} {}", shown.join(" "), display_cents.len());
}
What is printed?
Rust · terminal.sh
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
rustc --edition=2024 main.rs && ./main

Use the selected language’s command. The examples use standard array methods in TypeScript, iterator adapters in Rust, and algorithms or ranges in C++. The supplied collections remain fixed while each pipeline runs.

02Filtering

filter keeps some elements, and its place in the pipeline matters

The display now needs a premium-product selection. The report should include products with an original unit price of at least 500 cents, then add the handling charge for display. These pipelines place the test on different sides of that charge. Predict both lines.

main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
fn show(unitCents: &[i32]) -> String {
    let shown: Vec<String> = unitCents.iter().map(|cents| cents.to_string()).collect();
    shown.join(" ")
}

fn main() {
    let unitCents = [600, 475, 1200, 300];

    let map_first: Vec<i32> = unitCents
        .iter()
        .map(|cents| cents + 50)
        .filter(|cents| *cents >= 500)
        .collect();
    let filter_first: Vec<i32> = unitCents
        .iter()
        .filter(|cents| **cents >= 500)
        .map(|cents| cents + 50)
        .collect();

    println!("{}", show(&map_first));
    println!("{}", show(&filter_first));
}
What are the two lines?

03Folding

A fold needs a start value, and the start value decides the type

Before combining order lines, check how a fold calculates one line’s value. The factors are a unit price of 2.50 and a quantity of 3, represented together as numbers. This reduced probe multiplies them; the second fold checks an empty input or a different accumulator type. Predict both lines.

main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
fn main() {
    let factors = [2.5, 3.0];
    let empty: [f64; 0] = [];

    println!(
        "{}",
        factors.iter().fold(1.0, |product, factor| product * factor)
    );

    println!(
        "{:?}",
        empty
            .iter()
            .copied()
            .reduce(|product, factor| product * factor)
    );
}
What are the two lines?

04When the work happens

Eager arrays, lazy iterators and views run callbacks different numbers of times

A preview needs only the first eligible displayed price. The program counts how often the map callback runs before the first eligible displayed price is found. Predict the count.

main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
fn main() {
    let unitCents = [600, 475, 1200, 300];
    let mut calls = 0;

    let first = unitCents
        .iter()
        .map(|cents| {
            calls += 1;
            cents + 50
        })
        .find(|cents| *cents >= 500);

    println!("{} {}", calls, first.unwrap());
}
What is printed?

05Repair the order report

Premium lines, group totals, then the largest line

The shop needs three views of its orders: premium lines for review, totals for reconciliation, and each group’s largest line for inspection. A credit can have a negative line value; an empty group has no line to inspect.

Each file contains its imports, reader, parser and complete caller.

Repair the order report

Select by unit price, combine each group’s line values, then retain its actual largest line even when all its values are negative.

  1. easy · F-MFR-V4-1 List the premium lines
  2. medium · F-MFR-V4-2 Total each group
  3. hard · F-MFR-V4-3 Find each group’s largest line
In the frontend Map listed prices into display values Optional

A read-only shop preview receives dense price records with unique stable IDs and shows the handling charge on every entry. The calculation keeps those IDs so the framework can identify list entries.

Example.tsx
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
type Price = { id: string; unitCents: number };

export default function Prices({ prices }: { prices: Price[] }) {
  const display = prices.map((price) => ({
    id: price.id,
    cents: price.unitCents + 50
  }));

  return (
    <ul>
      {display.map((price) => (
        <li key={price.id}>{(price.cents / 100).toFixed(2)}</li>
      ))}
    </ul>
  );
}

The first map builds display data; the second maps it into list elements. Neither callback changes the incoming price records. Keys identify entries; the extra map does not add products.

Sources: React: Rendering lists,Svelte: Derived state,Svelte: Each blocks.

Sources

Report a problem in this lesson

For typos, mistakes and things that don’t work. We read every report and fix what’s wrong, but we don’t reply here, so a question won’t get an answer.