takeRightWhile()
takeRightWhile<
T>(array,predicate):T[]
Creates a slice of array with elements taken from the end while predicate returns truthy.
Type Parameters
T: T
The type of elements in the array.
Parameters
array: readonly T[]
The array to query.
predicate: (value, index, array) => boolean
The function invoked per iteration.
Returns: T[]
A new array of taken elements.
Since
2.0.0
Performance
O(n) time, stops at first falsy predicate result from end.
Also known as
takeLastWhile (Remeda, Ramda) · takeRightWhile (Lodash, es-toolkit, Modern Dash) · ❌ (Radashi, Effect, Antfu)
Example
const users = [
{ user: 'barney', active: false },
{ user: 'fred', active: true },
{ user: 'pebbles', active: true }
];
takeRightWhile(users, u => u.active);
// => [{ user: 'fred', active: true }, { user: 'pebbles', active: true }]
takeRightWhile([1, 2, 3, 4, 5], n => n > 3);
// => [4, 5]
How it works?
Takes elements from the end while predicate is true. Scans from right to left.
Use Cases
Get trailing valid entries 📌
Take elements from the end while they pass a condition. Perfect for extracting suffixes or recent valid sequences.
const data = [1, 2, -1, 3, 4, 5];
const validSuffix = takeRightWhile(data, (n) => n > 0);
// => [3, 4, 5]
Extract recent completed tasks
Get trailing items that match a status. Useful for showing "recently completed" or latest successes.
const tasks = [
{ status: "pending", name: "Task 1" },
{ status: "done", name: "Task 2" },
{ status: "done", name: "Task 3" },
{ status: "done", name: "Task 4" },
];
const recentlyCompleted = takeRightWhile(tasks, (t) => t.status === "done");
// => [Task 2, Task 3, Task 4]
Get trailing positive values
Extract suffix of values above a threshold. Perfect for trend analysis or recent performance extraction.
const metrics = [-5, 10, -2, 15, 20, 25];
const recentGrowth = takeRightWhile(metrics, (m) => m > 0);
// => [15, 20, 25]