Lodash Collection methods
What you’ll learn
- What to know before you start (see Prerequisites).
- How Lodash Collection helpers treat arrays and plain objects.
- How iteratees, predicates, and shorthand paths shorten real-world code.
- When native
map/filter/reducestays enough versus Lodash. - Where each
_.methodNamemaps on this site (/lodash/collection/...).
Prerequisites
Arrays, callbacks, and optional familiarity with Lodash array tutorials when your pipeline mixes reshaping with iteration.
- Higher-order functions: passing functions to
map-style APIs and understanding returned versus mutated data. - Objects as maps: reading
{ id: row }shapes—many grouping helpers output objects keyed by strings. - Modules: ESM
importor CommonJSrequireso the install snippets match your toolchain.
Key concepts
Lodash collection helpers reuse iteratees and predictable arity rules across APIs. These ideas unlock faster reading of signatures and TypeScript typings.
Collection shape
Arrays iterate by index; objects iterate enumerable string keys. Iteratees receive (value, index|key, collection).
Iteratee shorthand
Pass a property path string or key name—Lodash projects values before comparing or grouping.
Predicate
filter, find, every, and some share truthy/falsy semantics—return booleans for clarity.
Reduction
reduce threads an accumulator; choose initial seed carefully when collections may be empty.
Overview
Collection methods power dashboard queries—group rows, sort multi-column tables, sample QA fixtures, and flatten nested GraphQL edges—without reinventing iteration guards.
Transform
map, flatMap*, and invokeMap reshape each slot.
Select
filter, reject, partition, and find* isolate matches.
Aggregate
groupBy, countBy, keyBy, sortBy, orderBy.
⚖️ Lodash vs native iteration
Modern arrays already expose map, filter, and reduce. Lodash adds shorthand iteratees, object iteration, stable multi-sort helpers, and utilities like groupBy that would otherwise be manual bookkeeping.
| Situation | Prefer native | Consider Lodash |
|---|---|---|
| Single array, simple callback | map, filter, some | Often unnecessary unless nearby code already imports Lodash |
| Iterate object values | Object.entries + loop | map/forEach over object directly |
| Group list by field | reduce into a map | groupBy, countBy, keyBy |
| Multi-column ordering | Custom comparator | orderBy with iteratee arrays |
| Random sampling | Manual index math | sample, sampleSize, shuffle |
Install and import
Install once per project, then import collection helpers individually for tree shaking.
npm install lodash import groupBy from "lodash/groupBy";
import map from "lodash/map";
const rows = [{ dept: "ops", hours: 8 }, { dept: "ops", hours: 6 }];
groupBy(rows, "dept");
// → { ops: [{ dept: "ops", hours: 8 }, { dept: "ops", hours: 6 }] }
map({ a: 1, b: 2 }, (n) => n * 10);
// → [10, 20] 🔄 Returns and side effects
Most collection transformers allocate new data. Side effects belong in explicit callbacks—avoid surprising mutations inside shared iteratees.
| Style | Examples | Rule of thumb |
|---|---|---|
| New collection output | map, filter, sortBy, partition | Treat results as snapshots you can pass onward immutably. |
| Scalar / summary output | reduce, every, some, includes | Watch empty-input edge cases for reducers. |
| Callback-driven walk | forEach, forEachRight | Returns the original collection; effects live inside your iteratee. |
Suggested learning path
Walk these in order inside the REPL or Try-it labs once individual tutorials land.
💻 Environment and versions
- Lodash 4.x: the index below reflects the stable Collection surface shipped with
lodash@^4. - Browsers & Node: identical package; prefer per-method imports for bundlers.
- TypeScript: add
@types/lodashwhen relying on full typings—method imports still benefit.
Method index
URLs follow /lodash/collection/{method-kebab} (for example /lodash/collection/group-by). Links resolve once matching tutorials exist.
| Method | What it does |
|---|---|
_.countBy() | Create an object keyed by iteratee results with counts per group. |
_.every() | Return true if predicate holds for every element (short-circuits). |
_.filter() | Elements matching predicate; same spirit as Array.prototype.filter. |
_.find() | First element matching predicate; undefined when none match. |
_.findLast() | Last element matching predicate, scanning from the end. |
_.flatMap() | Map then flatten one level—handy for one-to-many projections. |
_.flatMapDeep() | Map then recursively flatten until only non-arrays remain. |
_.flatMapDepth() | Map then flatten up to a chosen depth. |
_.forEach() | Invoke iteratee for each entry; returns the collection for chaining. |
_.forEachRight() | Like forEach but walks elements from right to left. |
_.groupBy() | Bucket values into arrays keyed by iteratee output. |
_.includes() | Whether value appears in collection (SameValueZero for arrays). |
_.invokeMap() | Invoke a path/method name on each element, collecting results. |
_.keyBy() | Build an object keyed by iteratee result; last write wins on collisions. |
_.map() | Transform each element; works on arrays and plain objects. |
_.orderBy() | Sort iterates by one or more iteratees and orders (asc/desc). |
_.partition() | Split into [matches, rejects] by predicate. |
_.reduce() | Fold collection left-to-right with an accumulator. |
_.reduceRight() | Fold collection right-to-left with an accumulator. |
_.reject() | Opposite of filter—elements where predicate is falsy. |
_.sample() | Single random element from collection. |
_.sampleSize() | n distinct random elements (without replacement when possible). |
_.shuffle() | New array with elements in random order. |
_.size() | Length for arrays/strings; count enumerable own keys on plain objects. |
_.some() | Return true if predicate holds for any element (short-circuits). |
_.sortBy() | Stable sort by iteratee results (ties preserve prior order). |
Pitfalls to avoid
Shorthand surprises
Property paths return undefined for missing keys—filters may drop rows silently.
Empty collections
Provide an explicit accumulator when zero elements should still yield a defined summary.
Mutating inside callbacks
Lodash does not deep-clone inputs for you—pure iteratees keep pipelines predictable.
❓ FAQ
Summary
- Scope: Collection helpers unify iteration across arrays and objects with shared iteratee conventions.
- Bundles: import per method to keep payloads lean.
- Next steps: open Lodash _.countBy(), revisit Lodash array methods, or choose any row in the index.
_.map, _.filter, and friends accept objects as collections too—Lodash walks string keys and passes (value, key, collection) to your iteratee.
9 people found this page helpful
