Skip to main content
zerotal

Documentation


Documentation / @zerotal/core / index / Collection

Class: Collection<T>

Defined in: helpers/Collection.ts:27

Fluent wrapper around an array. Chain transformations (map, filter, where, pluck, …), read aggregates (sum, first, …), and unwrap with toArray. Most methods return a NEW Collection, leaving the original untouched, so chains read top-to-bottom.

Create one with the collect helper. Extend all instances at once with the static macro.

Example

const users = collect([
  { name: 'Alice', team: 'a', score: 90 },
  { name: 'Bob',   team: 'b', score: 70 },
  { name: 'Cara',  team: 'a', score: 85 },
]);

users
  .where('score', '>=', 80)   // keep Alice and Cara
  .map((u) => ({ ...u, name: u.name.toUpperCase() }))
  .pluck('name')              // Collection<string>
  .toArray();                 // ['ALICE', 'CARA']

Type Parameters

T

T

Constructors

Constructor

new Collection<T>(_items): Collection<T>

Defined in: helpers/Collection.ts:28

Parameters

_items

T[]

Returns

Collection<T>

Access

each()

each(fn): this

Defined in: helpers/Collection.ts:249

Run fn for each item (for side effects) and return the same Collection.

Parameters

fn

(item, index) => void

Returns

this


first()

first(fn?): T | undefined

Defined in: helpers/Collection.ts:283

The first item (optionally the first matching fn), or undefined.

Parameters

fn?

(item) => boolean

Returns

T | undefined


last()

last(fn?): T | undefined

Defined in: helpers/Collection.ts:291

The last item (optionally the last matching fn), or undefined.

Parameters

fn?

(item) => boolean

Returns

T | undefined


contains()

contains(valueOrFn): boolean

Defined in: helpers/Collection.ts:343

Whether the collection contains a value, or any item matching a predicate.

Parameters

valueOrFn

T | ((item) => boolean)

Returns

boolean

Aggregation

count()

count(): number

Defined in: helpers/Collection.ts:260

The number of items.

Returns

number


isEmpty()

isEmpty(): boolean

Defined in: helpers/Collection.ts:268

Whether the collection has no items.

Returns

boolean


isNotEmpty()

isNotEmpty(): boolean

Defined in: helpers/Collection.ts:275

Whether the collection has at least one item.

Returns

boolean


sum()

sum(key?): number

Defined in: helpers/Collection.ts:303

Sum the items, or the numeric value at key on each item.

Parameters

key?

keyof T

Returns

number


avg()

avg(key?): number

Defined in: helpers/Collection.ts:314

The mean of the items (or of key on each item); 0 when empty.

Parameters

key?

keyof T

Returns

number


min()

min(key?): number

Defined in: helpers/Collection.ts:323

The smallest value (or smallest key value); 0 when empty.

Parameters

key?

keyof T

Returns

number


max()

max(key?): number

Defined in: helpers/Collection.ts:333

The largest value (or largest key value); 0 when empty.

Parameters

key?

keyof T

Returns

number


length

Get Signature

get length(): number

Defined in: helpers/Collection.ts:380

The number of items (property form of Collection.count).

Returns

number

Conversion

toArray()

toArray(): T[]

Defined in: helpers/Collection.ts:356

A shallow copy of the underlying items as a plain array.

Returns

T[]


toJson()

toJson(): string

Defined in: helpers/Collection.ts:364

The items serialized to a JSON string.

Returns

string


values()

values(): T[]

Defined in: helpers/Collection.ts:372

A shallow copy of the items (alias of Collection.toArray).

Returns

T[]


[iterator]()

[iterator](): Iterator<T>

Defined in: helpers/Collection.ts:388

Iterate the items directly, e.g. in a for...of loop or spread.

Returns

Iterator<T>

Mutation

macro()

static macro(name, fn): void

Defined in: helpers/Collection.ts:421

Register a macro (custom method) on all Collection instances.

The function is added to Collection.prototype, so it is available on every collect() result immediately. Use this inside the function to access the collection's own methods (this.filter(), this.map(), etc.).

Add a module augmentation to your project for full TypeScript type safety:

Parameters

name

string

fn

(this, ...args) => unknown

Returns

void

Example

// In AppServiceProvider.onBooted():
Collection.macro('filterActive', function(this: Collection<{ active: boolean }>) {
  return this.filter((item) => item.active);
});

// In types.d.ts (for type safety):
declare module '@zerotal/core' {
  interface Collection<T> {
    filterActive(): Collection<T & { active: boolean }>;
  }
}

// In a controller:
const active = collect(users).filterActive();

Transformation

map()

map<U>(fn): Collection<U>

Defined in: helpers/Collection.ts:36

Map every item through fn, returning a new Collection of the results.

Type Parameters

U

U

Parameters

fn

(item, index) => U

Returns

Collection<U>


flatMap()

flatMap<U>(fn): Collection<U>

Defined in: helpers/Collection.ts:44

Map each item to an array and flatten the results one level.

Type Parameters

U

U

Parameters

fn

(item, index) => U[]

Returns

Collection<U>


filter()

filter(fn): Collection<T>

Defined in: helpers/Collection.ts:52

Keep only items for which fn returns truthy.

Parameters

fn

(item, index) => boolean

Returns

Collection<T>


reject()

reject(fn): Collection<T>

Defined in: helpers/Collection.ts:60

Inverse of Collection.filter — drop items for which fn returns truthy.

Parameters

fn

(item, index) => boolean

Returns

Collection<T>


where()

where(key, operatorOrValue, value?): Collection<T>

Defined in: helpers/Collection.ts:74

Filter by a key/value pair (optionally with operator). With two arguments the operator defaults to =; supported operators are =/==, !=/<>, >, >=, <, <=.

Parameters

key

keyof T

operatorOrValue

unknown

value?

unknown

Returns

Collection<T>

Example

collect(users).where('active', true)
collect(orders).where('total', '>', 100)

whereIn()

whereIn<K>(key, values): Collection<T>

Defined in: helpers/Collection.ts:112

Filter to items whose key value is in the list.

Type Parameters

K

K extends string | number | symbol

Parameters

key

K

values

T[K][]

Returns

Collection<T>


whereNotIn()

whereNotIn<K>(key, values): Collection<T>

Defined in: helpers/Collection.ts:120

Filter to items whose key value is NOT in the list.

Type Parameters

K

K extends string | number | symbol

Parameters

key

K

values

T[K][]

Returns

Collection<T>


pluck()

pluck<K>(key): Collection<T[K]>

Defined in: helpers/Collection.ts:128

Extract one key from each item into a new Collection of those values.

Type Parameters

K

K extends string | number | symbol

Parameters

key

K

Returns

Collection<T[K]>


groupBy()

groupBy<K>(keyOrFn): Record<K, T[]>

Defined in: helpers/Collection.ts:136

Group items into a plain object keyed by a property or callback result.

Type Parameters

K

K extends string

Parameters

keyOrFn

keyof T | ((item) => K)

Returns

Record<K, T[]>


keyBy()

keyBy<K>(key): Record<string, T>

Defined in: helpers/Collection.ts:155

Index items into a plain object keyed by a property — last duplicate wins.

Type Parameters

K

K extends string | number | symbol

Parameters

key

K

Returns

Record<string, T>


sortBy()

sortBy<K>(key, direction?): Collection<T>

Defined in: helpers/Collection.ts:167

Return a new Collection sorted by a key, ascending by default.

Type Parameters

K

K extends string | number | symbol

Parameters

key

K

direction?

"asc" | "desc"

Returns

Collection<T>


unique()

unique(key?): Collection<T>

Defined in: helpers/Collection.ts:182

Remove duplicate values (for primitive collections) or by key.

Parameters

key?

keyof T

Returns

Collection<T>


chunk()

chunk(size): Collection<T[]>

Defined in: helpers/Collection.ts:199

Split into a Collection of arrays, each at most size items long.

Parameters

size

number

Returns

Collection<T[]>


flatten()

flatten(): Collection<T extends unknown[] ? T[number] : T>

Defined in: helpers/Collection.ts:211

Flatten a Collection of arrays one level deep.

Returns

Collection<T extends unknown[] ? T[number] : T>


reverse()

reverse(): Collection<T>

Defined in: helpers/Collection.ts:221

Return a new Collection with the items in reverse order.

Returns

Collection<T>


take()

take<N>(count?): N extends undefined ? T | undefined : Collection<T>

Defined in: helpers/Collection.ts:230

Take the first count items as a new Collection, or — when called with no argument — return the single first item (or undefined).

Type Parameters

N

N extends number | undefined = undefined

Parameters

count?

N

Returns

N extends undefined ? T | undefined : Collection<T>


skip()

skip(count): Collection<T>

Defined in: helpers/Collection.ts:241

Skip the first count items, returning the rest as a new Collection.

Parameters

count

number

Returns

Collection<T>