Skip to main content

Harshal V. LADHE

First N Matches from Any Iterable with filter() and take()

Get the first N matches and stop reading.
Read the full tutorial: Iterator Helpers: Lazy Pipelines over Any Iterator
Published at:
Last updated:
Estimated reading time:4 min read
Cover for 'First N Matches from Any Iterable', showing filter().slice() checking every value while filter().take(3) stops at the third match.(opens full-size image in a new tab)
filter().take(3) stops at the third match after 3,000 checks, where filter().slice(0, 3) makes 1,000,000.

Introduction

"Give me the first three errors" is usually written as lines.filter(isError).slice(0, 3). It gives the right answer, but filter() checks every line and builds an array of every match before slice() keeps three of them. On a million lines where the first three errors are near the top, almost all of that work is thrown away.

With ES2025 iterator helpers, the same request can stop as soon as it has enough. filter() and take() on an iterator are lazy, so the predicate runs only until the third match turns up, and nothing else is read.

The Code

function firstMatches(iterable, predicate, n) {
  return Iterator.from(iterable).filter(predicate).take(n).toArray();
}

How It Works

  1. Iterator.from(iterable) turns any iterable, such as an array, a Set, a Map's values, a NodeList or a generator, into an iterator that has the helper methods. If it's given an iterator that already has them, it returns it unchanged.
  2. .filter(predicate) returns a new iterator. It doesn't run yet.
  3. .take(n) wraps that in another iterator that hands out at most n values.
  4. .toArray() is what starts the work. It asks take() for values one at a time, take() asks filter(), and filter() reads from the source until the predicate passes. Each match travels straight through to the result before the next value is read.
  5. Once take() has given out n values and is asked for another, it calls return() on the source instead of reading further, and toArray() returns the array.

The predicate runs on the values up to and including the nth match, and no further.

Example Usage

The First Errors in a Log

const log = [
  "INFO start",
  "ERROR disk full",
  "INFO retry",
  "ERROR timeout",
  "ERROR disk full",
  "INFO done"
];

firstMatches(log, (line) => line.startsWith("ERROR"), 2);
// ["ERROR disk full", "ERROR timeout"]

Values from a Map

const users = new Map([
  [1, { name: "Ada", active: true }],
  [2, { name: "Bo", active: false }],
  [3, { name: "Cy", active: true }],
  [4, { name: "Di", active: true }]
]);

firstMatches(users.values(), (user) => user.active, 2).map((user) => user.name);
// ["Ada", "Cy"]

An Infinite Sequence

Because nothing is read ahead, the source doesn't need an end. This is where filter().slice() can't help at all:

function* integersFrom(start) {
  let n = start;
  while (true) yield n++;
}

function isPrime(n) {
  for (let d = 2; d * d <= n; d++) {
    if (n % d === 0) return false;
  }
  return n > 1;
}

firstMatches(integersFrom(2), isPrime, 5); // [2, 3, 5, 7, 11]

The First Invalid Form Fields

A NodeList is iterable, so it can go straight in:

const fields = document.querySelectorAll("input, select, textarea");
const firstInvalid = firstMatches(fields, (field) => !field.validity.valid, 3);

firstInvalid[0]?.focus();

Counting the Work Saved

const numbers = Array.from({ length: 1_000_000 }, (_, i) => i);
let checks = 0;
const matches = (n) => {
  checks++;
  return n % 1000 === 999;
};

firstMatches(numbers, matches, 3);
console.log(checks); // 3000

checks = 0;
numbers.filter(matches).slice(0, 3);
console.log(checks); // 1000000

Both return [999, 1999, 2999]. The lazy version stops at the third match, and the array version checks all million numbers and builds a 1,000-element array first.

Use Cases

  • Search-as-you-type previews that show the first few matches from a large list.
  • Validation summaries that report the first few problems rather than every one.
  • Log and data scanning, where the first few hits are enough to act on.
  • Generated sequences, such as IDs, dates or numbers, where you want the first n that meet a condition.

Notes & Tips

  • Fewer than n is fine: if the source runs out first, you get the matches there were, or [] if none. n = 0 also returns [], without running the predicate at all.
  • Invalid n throws: take() throws a RangeError for a negative number or NaN, before anything is read.
  • The predicate's second argument is a counter of values seen so far, starting at 0, not an array index into a filtered list. There's no third "whole collection" argument as there is with Array.prototype.filter().
  • Regex matches are lazy too: text.matchAll(regex) returns an iterator, so text.matchAll(/id=(\d+)/g).take(2).map((m) => Number(m[1])).toArray() stops scanning after two matches.
  • Generators are closed properly: when take() stops early it calls return() on the source, so a generator's finally block runs.
  • Small arrays don't need this: for a few hundred items that are already in an array, filter().slice() is just as good. The lazy version pays off on large or unbounded sources and expensive predicates.
  • Browser support: iterator helpers work in Chrome and Edge 122, Firefox 131, Safari 18.4 and Node 22. For older environments, use a polyfill such as core-js, or the plain loop below.
function firstMatches(iterable, predicate, n) {
  if (!(n >= 0)) throw new RangeError(`Invalid n: ${n}`); // as take() does, NaN included

  const matches = [];
  if (n < 1) return matches;

  for (const value of iterable) {
    if (predicate(value)) {
      matches.push(value);
      if (matches.length >= n) break; // break closes the source, as take() does
    }
  }

  return matches;
}

Frequently Asked Questions

Key Takeaway

Iterator.from(source).filter(predicate).take(n).toArray() returns the first n matches and stops reading the moment it has them. It works on any iterable, including ones that never end, and it closes the source when it's done. Keep filter().slice() for small arrays, and use this when the source is large, unbounded or expensive to check. The full tour of iterator helpers is in Iterator Helpers: Lazy Pipelines over Any Iterator.

Changelog

  • — Initial publication.
This snippet is licensed under CC BY 4.0 by the author.

Share this snippet

Spotted a mistake or something outdated in this snippet? Suggest a correction.

  • Bytes to Hex and Back with Uint8Array.fromHex() and toHex()

    Convert bytes to hex and back without padStart loops.
    Encode bytes as hex with ES2026's Uint8Array toHex(), decode with fromHex() and setFromHex(), with SHA-256 digests, colours, error cases and a padStart fallback.
    Published at:
  • Encapsulation with Private Class Fields

    Use native #private syntax to protect class properties in JavaScript.
    Implement native engine-level privacy in your OOP structures using ES2022+ private class fields and memory-efficient prototype methods.
    Published at:
  • Deep Freeze Objects in JavaScript

    Recursively lock every object level for true immutability
    Lock objects and their children immutably — prevent accidental mutations and enforce deep immutability in strict mode.
    Published at: