stacks-collections

$npx mdskill add stacksjs/stacks/stacks-collections

Chain array operations and manipulate collections using Laravel-style methods.

  • Provides fluent collection methods like map, filter, reduce, and groupBy.
  • Depends on @stacksjs/collections which wraps ts-collect.
  • Selects operations based on chained method calls on the collect() result.
  • Returns transformed arrays or aggregated values like sum, avg, or grouped objects.

SKILL.md

.github/skills/stacks-collectionsView on GitHub ↗
---
name: stacks-collections
description: Use when working with collection data structures in Stacks — chaining array operations, Laravel-style collection methods, mapping, filtering, reducing, or grouping. Covers @stacksjs/collections which wraps ts-collect.
license: MIT
compatibility: Bun >= 1.3.0, TypeScript
allowed-tools: Read Edit Write Bash Grep Glob
---

# Stacks Collections

## Key Paths
- Core package: `storage/framework/core/collections/src/`
- Source: `storage/framework/core/collections/src/index.ts`
- Package: `@stacksjs/collections`

## API

The package re-exports `collect` from `ts-collect`:

```typescript
import { collect } from '@stacksjs/collections'
```

## Usage

```typescript
import { collect } from '@stacksjs/collections'

// Basic operations
const result = collect([1, 2, 3, 4, 5])
  .filter(n => n > 2)
  .map(n => n * 2)
  .toArray()
// [6, 8, 10]

// Aggregation
collect([10, 20, 30]).sum()     // 60
collect([10, 20, 30]).avg()     // 20
collect([10, 20, 30]).min()     // 10
collect([10, 20, 30]).max()     // 30

// Grouping
collect(users).groupBy('role')
// { admin: [...], user: [...] }

// Sorting
collect(items).sortBy('price').toArray()
collect(items).sortByDesc('price').toArray()

// Unique
collect([1, 2, 2, 3, 3]).unique().toArray()  // [1, 2, 3]

// First / Last
collect([1, 2, 3]).first()     // 1
collect([1, 2, 3]).last()      // 3

// Chunk
collect([1, 2, 3, 4, 5]).chunk(2).toArray()
// [[1, 2], [3, 4], [5]]

// Pluck
collect(users).pluck('name').toArray()  // ['Alice', 'Bob']

// Contains
collect([1, 2, 3]).contains(2)  // true

// Reduce
collect([1, 2, 3]).reduce((sum, n) => sum + n, 0)  // 6
```

## Laravel-Style Methods

The `ts-collect` library provides a comprehensive Laravel Collection-compatible API including:

`all`, `avg`, `chunk`, `collapse`, `combine`, `concat`, `contains`, `count`, `countBy`, `crossJoin`, `dd`, `diff`, `diffAssoc`, `diffKeys`, `dump`, `duplicates`, `each`, `every`, `except`, `filter`, `first`, `firstOrFail`, `firstWhere`, `flatMap`, `flatten`, `flip`, `forget`, `forPage`, `get`, `groupBy`, `has`, `implode`, `intersect`, `intersectByKeys`, `isEmpty`, `isNotEmpty`, `join`, `keyBy`, `keys`, `last`, `macro`, `map`, `mapInto`, `mapSpread`, `mapToGroups`, `mapWithKeys`, `max`, `median`, `merge`, `mergeRecursive`, `min`, `mode`, `nth`, `only`, `pad`, `partition`, `pipe`, `pluck`, `pop`, `prepend`, `pull`, `push`, `put`, `random`, `reduce`, `reject`, `replace`, `replaceRecursive`, `reverse`, `search`, `shift`, `shuffle`, `skip`, `skipUntil`, `skipWhile`, `slice`, `sole`, `some`, `sort`, `sortBy`, `sortByDesc`, `sortDesc`, `sortKeys`, `sortKeysDesc`, `splice`, `split`, `sum`, `take`, `takeUntil`, `takeWhile`, `tap`, `times`, `toArray`, `toJson`, `transform`, `union`, `unique`, `uniqueStrict`, `unless`, `unlessEmpty`, `unlessNotEmpty`, `unwrap`, `values`, `when`, `whenEmpty`, `whenNotEmpty`, `where`, `whereBetween`, `whereIn`, `whereInstanceOf`, `whereNotBetween`, `whereNotIn`, `whereNotNull`, `whereNull`, `wrap`, `zip`

## Gotchas
- **Thin wrapper** — re-exports `collect` from `ts-collect`, no custom additions
- **Collections are immutable** — operations return new collection instances
- **For simple array operations** — `@stacksjs/arrays` may be more appropriate
- **Laravel API compatibility** — method names and behavior match Laravel's Collection class
- **Not used for ORM results** — ORM queries return plain arrays, not collections. Wrap with `collect()` if needed

More from stacksjs/stacks

SkillDescription
stacks-actionsUse when working with Stacks server actions — creating actions in app/Actions/, auto-generated API actions from the useApi model trait, the 80+ default framework actions (auth, dashboard, commerce, content, deployment, jobs), action request/response handling, or action registration. Covers @stacksjs/actions and storage/framework/defaults/actions/.
stacks-aiUse when integrating AI capabilities into a Stacks application — using Anthropic/OpenAI/Ollama/AWS Bedrock drivers, image generation (DALL-E), vision analysis, RAG/vector search, embeddings, MCP (Model Context Protocol) clients, text summarization, sentiment analysis, content classification, personalization, or the buddy AI assistant. Covers @stacksjs/ai and config/ai.ts.
stacks-aliasUse when working with path aliases in a Stacks project — import resolution, module aliasing, or debugging import paths. Covers @stacksjs/alias which defines 260+ path mappings for the entire framework.
stacks-analyticsUse when adding analytics to a Stacks application — configuring Fathom or self-hosted analytics, generating tracking scripts, privacy-friendly analytics setup, or the analytics configuration. Covers @stacksjs/analytics and config/analytics.ts.
stacks-apiUse when building, modifying, or debugging API endpoints in a Stacks application — defining routes, handling requests, API middleware, working with the API server, HTTP client (fetcher), API resources, or OpenAPI generation. Covers both @stacksjs/api utilities and the stacks-api server implementation.
stacks-arraysUse when working with array utilities in Stacks — statistical operations (average, median, mode, standard deviation, z-score, percentile, covariance), array manipulation (unique, flatten, partition, shuffle, sample, move), containment checks, or the Arr facade. Covers @stacksjs/arrays.
stacks-authUse when implementing authentication, authorization, passkeys, TOTP/2FA, RBAC, gates, policies, session auth, token management, email verification, password resets, or rate limiting in a Stacks application. Covers the @stacksjs/auth package, config/auth.ts, app/Gates.ts, and app/Middleware/.
stacks-auto-importsUse when working with the Stacks auto-import system — understanding how browser and server auto-imports work, configuring auto-imported functions/models/composables, the auto-import manifests, type generation, or how globals are injected. Covers the auto-import pipeline at storage/framework/auto-imports/.
stacks-brandkitUse when defining or exploring a brand identity for a Stacks project and you want premium brand-kit REFERENCE IMAGES first - logo directions, palettes, typography specimens, identity boards, and application/mockup decks. Generates IMAGES ONLY, never code. Trained for minimalist, cinematic, editorial, dark-tech, luxury, cultural, security, gaming, developer-tool, and consumer-app brand systems with intentional logo concepting, sparse type, strong symbolic meaning, and disciplined palettes a coding step can build against.
stacks-browseUse for headless browser QA on Stacks applications — navigation, screenshots, responsive testing, console/network monitoring, and accessibility snapshots. Dependency-free: drives a system browser over the Chrome DevTools Protocol using only Bun (no Playwright/Puppeteer). Invoke with /stacks-browse.