Data shapes · 12 min · free lesson

Array methods vs iterators

map and filter on an array run at once and build new arrays; Rust's iterator adapters do nothing until a consumer such as sum, find or collect pulls values.

Core idea

Iterator adapters are lazy: a consumer such as sum, find, collect or a for loop drives the work, one item at a time.

JavaScript (Node.js) and Rust, side by side

JavaScript (Node.js) map runs eagerly, so the search for the first big order still maps all three orders.
const orders = [
  { cents: 1200, paid: true },
  { cents: 300, paid: false },
  { cents: 450, paid: true },
];

let calls = 0;
const paidTotal = orders
  .filter((o) => o.paid)
  .map((o) => { calls += 1; return o.cents; }) // runs now, builds an array
  .reduce((sum, c) => sum + c, 0);
console.log(paidTotal, calls);

const firstBig = orders.map((o) => { calls += 1; return o.cents; }).find((c) => c > 1000);
console.log(firstBig, calls); // map ran for all three orders
Rust The closure counter shows the difference: two calls for the total, and the search stops after one more.
struct Order {
    cents: u64,
    paid: bool,
}

fn main() {
    let orders = [
        Order { cents: 1200, paid: true },
        Order { cents: 300, paid: false },
        Order { cents: 450, paid: true },
    ];
    let mut calls = 0;
    let paid_total: u64 = orders
        .iter()
        .filter(|o| o.paid)
        .map(|o| { calls += 1; o.cents })
        .sum();
    println!("{paid_total} {calls}");

    let first_big = orders.iter().map(|o| { calls += 1; o.cents }).find(|&c| c > 1000);
    println!("{first_big:?} {calls}");
}
What changes
JavaScript (Node.js)Rust
Each array method runs immediately over every element.Adapters such as map and filter run only when a consumer pulls items.
arr.map(f).find(p) calls f for every element.iter.map(f).find(p) stops calling f after the first match.
Each stage allocates a new array.No intermediate collection is built unless you call collect.
reduce((s, x) => s + x, 0)sum(), or fold(0, |s, x| s + x) for a general accumulator.

Understand it

orders.filter(...).map(...).reduce(...) runs each stage over the whole array and allocates an intermediate array between stages. Rust's orders.iter().filter(...).map(...).sum() first builds a description of the work. Nothing happens until sum asks for the first item; then each order flows through filter and map one at a time, with no intermediate Vec.

Laziness changes what runs. In the JavaScript example, map(...).find(...) calls the mapping function for all three orders before find looks at one. The Rust pipeline stops at the first match, so its closure runs once. A pipeline that is never consumed does nothing at all, which is why rustc warns that an unused Map must be used in the practice code.

The names mostly carry over: map, filter and find are the same, some is any, every is all, reduce with an initial value is fold, and flatMap is flat_map. The length of a filtered result is count(), and collect::<Vec<_>>() gives you a collection back. There is no index argument; add .enumerate() to get (index, item) pairs.

Watch what the iterator yields. iter() yields references (&Order), iter_mut() yields &mut Order, and into_iter() on a Vec yields owned values and consumes the vector. That is why the closures read o.cents through a reference, and why find(|&c| c > 1000) destructures the &u64 it receives.

The JavaScript (Node.js) habit, written in Rust

This is how the JavaScript (Node.js) version usually looks on a first attempt in Rust. Predict what rustc says before you read the explanation.

fn main() {
    let prices = vec![3, 7, 12];
    prices.iter().map(|p| {
        println!("checking {p}");
        p * 2
    });
    println!("done");
}

Practise this code in Playground ↗

Try it

Port the JavaScript firstPriceOver shown at the top of solution.rs, but keep the Rust version lazy: call price_of only until the first price above limit is found. The harness counts the calls. In the Crabrix app, open the compiler lab and complete the supplied function in solution.rs. The reading question is a separate exercise.

What success looks like: The local compiler accepts the changed solution and the separate verification harness passes every case, including the number of price_of calls and an empty slice. Printing a success message alone does not complete this lab.

Check your understanding

In the practice code, what has map done by the time done prints?

Reveal the answer
  1. Nothing: no consumer such as sum, collect or for asked for a value
  2. It doubled all three prices into a new vector, like Array.prototype.map
  3. It doubled the first price and then paused

An adapter only describes work. Without a consumer the closure never runs, and rustc warns that the Map must be used.

Go deeper

Common misconception: “iter().map(...) works like Array.prototype.map: it builds the new values right away.”

map returns a lazy adapter. The closure runs only when a consumer pulls an item, and only for the items it pulls.

  1. Read the pipeline: orders.iter() yields &Order. filter keeps the paid orders, map turns each into its cents, and sum is the only consumer.
  2. Count the work: sum pulls items one at a time. Only the two paid orders reach map, so calls becomes 2; the unpaid order never does.
  3. Compare with evidence: Run it: 1650 2, then Some(1200) 3. find stopped after the first order, while JavaScript's map had already run for all three.

Transfer challenge: Insert .inspect(|o| println!("saw {}", o.cents)) right after orders.iter() in both pipelines and predict the printed lines. Then add .collect::<Vec<_>>() after the second map, iterate that vector for the find, and count the calls again.

Connections

  • null, undefined and ?? vs Option: Absence as Option<T>
  • Objects and Map vs HashMap: Keyed data with HashMap and entry
Side-by-side comparison: the JavaScript (Node.js) version on the left, the Rust version on the right, then 4 rows naming what changes.
Array methods vs iterators: the same task in JavaScript (Node.js) and in Rust, with the differences that matter.
Learn this lesson with AI

Paste this into Claude, Codex, Cursor or another agent connected to Crabrix Academy. It contains only this lesson’s public details.

I'm learning Rust with Crabrix Academy. Teach me this lesson with the Crabrix Academy tools.
Lesson: Array methods vs iterators (courseId "rust-for-nodejs-developers", lessonId "node-array-methods-to-iterators")
Link: https://crabrix.com/learn/rust-for-nodejs-developers/node-array-methods-to-iterators/
Goal: Iterator adapters are lazy: a consumer such as sum, find, collect or a for loop drives the work, one item at a time.
Practice: open the starter in the Crabrix Playground (https://crabrix.com/playground/?lesson=rust-for-nodejs-developers/node-array-methods-to-iterators) and I will write the code there.
Explain it step by step for my level, let me write the code myself, give hints before any solution, and do not mark anything as passed: only Crabrix checks do that.

In Claude Code, Codex or Cursor, paste it into a chat with Crabrix Academy connected. On a phone, the Claude and ChatGPT apps open the same links.