Skip to main content

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]