Understanding Lodash takeRightWhile Predicate
This article provides an overview of how the
_.takeRightWhile method in the Lodash JavaScript library
uses predicates to extract array elements. You will learn the mechanics
behind its extraction process, what predicate is used by default, and
how you can supply custom functions or shorthand identifiers to filter
items from the end of an array.
How _.takeRightWhile
Works
The _.takeRightWhile method creates a slice of an
array with elements taken from the end. It iterates through
the array from right to left, evaluating each element against a
predicate. Elements continue to be collected as long as the predicate
returns a truthy value. The moment the predicate returns a falsy value,
extraction stops, and the collected elements are returned in their
original relative order.
The Default Predicate:
_.identity
If no predicate argument is provided to
_.takeRightWhile, Lodash defaults to using
_.identity.
_.takeRightWhile(array, [predicate=_.identity])The _.identity function simply returns the first
argument it receives (n => n). When relying on this
default:
- Truthy values (like non-zero numbers, non-empty strings, and objects) continue the extraction.
- Falsy values (
false,0,"",null,undefined, andNaN) immediately halt extraction.
Custom Function Predicate
You can provide a custom predicate function to define your own extraction logic. Lodash invokes this function with three arguments:
value: The current element being evaluated.index: The index of the current element.array: The original array being iterated over.
const numbers = [1, 2, 3, 4, 5, 6];
// Takes elements from the right while they are greater than 3
const result = _.takeRightWhile(numbers, n => n > 3);
// Output: [4, 5, 6]Iteration starts at 6 and moves backward. Once it
reaches 3, the condition 3 > 3 evaluates to
false, and the process halts.
Supported Predicate Shorthands
Lodash provides shorthand notations by running the predicate through
_.iteratee. This allows you to supply data structures
instead of writing out full callback functions:
Object Shorthand (
_.matches): Compares properties to check for exact key-value matches.const users = [ { user: 'barney', active: true }, { user: 'fred', active: false }, { user: 'pebbles', active: false } ]; _.takeRightWhile(users, { active: false }); // Output: [{ user: 'fred', active: false }, { user: 'pebbles', active: false }]Matches Property Shorthand (
_.matchesProperty): Compares a specific key-value pair provided as a two-element array._.takeRightWhile(users, ['active', false]); // Output: [{ user: 'fred', active: false }, { user: 'pebbles', active: false }]Property Shorthand (
_.property): Checks the truthiness of a specific property value._.takeRightWhile(users, 'active'); // Output: [] (stops immediately because the last element has active: false)