Lodash _.partition() method
What you’ll learn
- How
_.partition(collection, predicate)produces[pass, fail]in one pass. - Using shorthand predicates on objects—same ergonomics as
filter. - Trade-offs versus paired
filter/rejectcalls or booleangroupBy. - Try each example in the editor (
?tryit=1,2,3) with Lodash from a CDN.
Prerequisites
Skim _.filter() so predicate iteratees feel familiar—partition is the dual-output variant.
- You understand predicates as functions returning truthy/falsy.
- You can open Try-it labs or run snippets locally.
Overview
_.partition answers “give me both piles” without walking the collection twice or juggling temporary flags.
Tuple output
Destructuring-friendly [truthy, falsy] arrays.
Single pass
Predicate evaluated once per element.
Iteratee sugar
Reuse matchers from filter/map pipelines.
Syntax
_.partition(collection, predicate) - collection: array or plain object Lodash can iterate.
- predicate: invoked as
(value, index|key, collection); truthy routes to bucket 0. - Returns:
[passArray, failArray]—both are new arrays.
Separate even and odd numbers
First tuple holds predicate successes—here remainders equal zero.
import partition from "lodash/partition";
partition([1, 2, 3, 4], (n) => n % 2 === 0);
// → [[2, 4], [1, 3]] Shorthand: partition by done
A string iteratee reads that property—truthy values land in the first bucket.
import partition from "lodash/partition";
partition(
[
{ id: 1, label: "Write", done: true },
{ id: 2, label: "Ship", done: false }
],
"done"
);
// → [[completed rows], [pending rows]] Split strings by length rule
Anything longer than two characters becomes its own pile.
import partition from "lodash/partition";
partition(["hi", "hello", "x"], (word) => word.length > 2);
// → [["hello"], ["hi", "x"]] 📋 _.partition vs filter/reject, groupBy
| API | Output | Best when |
|---|---|---|
_.partition(collection, predicate) | [pass, fail] | You always need both groups from one predicate |
_.filter + _.reject | Two independent arrays | Convenient if passes happen far apart in code |
_.groupBy(collection, predicate) | Keys "true"/"false" | More than two buckets or dynamic grouping labels |
Pitfalls to avoid
Exactly two buckets
Need three or more piles—compose nested partitions or switch to groupBy.
Predicate cost
Heavy predicates still run once per element—cache derives before hot loops.
Index confusion
Remember index 0 is truthy hits—name destructured vars explicitly.
❓ FAQ
Summary
- Purpose:
_.partition(collection, predicate)splits elements into truthy and falsy buckets. - Contrast: chained filter/reject evaluates predicates twice.
- Next: Lodash _.reduce(), Lodash _.orderBy() (previous), or collection hub.
_.partition always returns a two-element array: index 0 holds elements where the predicate was truthy, index 1 holds the rest—ideal for destructuring const [pass, fail] = _.partition(...).
6 people found this page helpful
