Skip to content

Collection

A fluent, chainable wrapper for arrays. Filter, sort, group, aggregate, paginate — top-to-bottom, no intermediate variables, no Lodash-style standalone calls. The collection is immutable by default (every reshape returns a new collection) and a native Iterable (spread, destructure, for-of all work without .all()).

Highlighted features

Chainable top-to-bottom

Read a pipeline as a recipe — .where().groupBy().map().sortByDesc().take(). No temp vars, no nested calls.

Operator-based filtering

.where(“total”, ”>”, 100), .where(“status”, “in”, [“paid”,“shipped”]), .where(“notes”, “empty”) — readable as SQL.

Immutable by default

sort, reverse, shift, pop all leave the original untouched — they clone, then return.

groupBy + aggregate

.groupBy(“customerId”) hands you buckets; chain .sum / .avg / .max / .count on each one.

Native Iterable

Spread, destructure, for-of, Array.from all work without calling .all().

Dot-notation keys

Every keyed helper accepts paths: .sum(“total.price”), .sortBy(“address.city”), .pluck(“user.email”).

Install

Terminal window
npm install @mongez/collection

Runtime deps: @mongez/reinforcements and @mongez/supportive-is.

Quick peek

import { collect } from "@mongez/collection";
const topSpenders = collect(orders)
.where("status", "paid")
.where("total", ">", 100)
.groupBy("customerId")
.map(bucket => ({
customerId: bucket.customerId,
spent: collect(bucket.items).sum("total"),
}))
.sortByDesc("spent")
.take(10)
.all();

Operator-based filtering, group-and-aggregate, sorted top-N — one chain reading top-to-bottom.

Construction patterns

import { collect, ImmutableCollection } from "@mongez/collection";
collect([1, 2, 3]); // from an array
collect(otherCollection); // from another collection
ImmutableCollection.create(5, i => ({ slot: i })); // N items via callback
collect.create(5, 0); // [0, 0, 0, 0, 0]
collect.fromIterator(new Set([1, 2, 3])); // from any iterable

Key pitfalls

  • toArray() / all() return the live underlying array. Use [...c] or Array.from(c) if you need a defensive copy.
  • shift() and pop() do NOT mutate — they’re item readers. Use c.skip(1) / c.skipLast(1) to drop.
  • Items with .get(key) methods are honoured automatically — model classes work without adapters.

Where to go next