Skip to content
Eugene Lazutkin edited this page Jun 26, 2026 · 1 revision

merge

K-way merge of two or more sorted streams into one sorted stream. Duplicates are preserved — every item from every input appears in the output (use union to deduplicate). The foundational sorted-stream operation.

import merge from 'stream-sorting/sorted/merge.js';

// streamA and streamB each sorted ascending
for await (const v of merge([streamA, streamB])) {
  // all items, in sorted order
}

streams is an array of AsyncIterable<T> | Iterable<T>, each already sorted by the same order; the result is an AsyncIterable<T>. Ties keep input order (lower stream index first). Convert at the boundary you need (readableFrom(...), ReadableStream.from(...)).

Options

Option Type Default Description
compare (a, b) => number natural order Orders items (Array.prototype.sort semantics). compare OR lessFn.
lessFn (a, b) => boolean Strict-less comparator. compare OR lessFn.

The default natural order works for primitives; object streams need an explicit comparator. An out-of-order input throws at runtime.

See also

union, intersection, difference, sort.

Clone this wiki locally