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]
Extract recent unread notificationsβ
Take trailing unread notifications for a notification badge count. Perfect for notification centers and inbox indicators.
const notifications = [
{ id: 1, read: true, text: "Welcome" },
{ id: 2, read: true, text: "New feature" },
{ id: 3, read: false, text: "New comment" },
{ id: 4, read: false, text: "New follower" },
{ id: 5, read: false, text: "Mention in #general" },
];
const recentUnread = takeRightWhile(notifications, (n) => !n.read);
// => [New comment, New follower, Mention]
setBadgeCount(recentUnread.length); // Show "3" on bell icon