dropRightWhile()
dropRightWhile<
T>(array,predicate):T[]
Creates a slice of array excluding elements dropped from the end. Elements are dropped until predicate returns falsey.
Type Parameters
T: T
The type of elements in the array.
Parameters
array: readonly T[]
The source array to query.
predicate: (value, index, array) => boolean
The function invoked per iteration.
Returns: T[]
A new array with the trailing elements dropped.
Since
2.0.0
Performance
O(n) time & space. Uses for loop with early return (break) for optimal performance when dropping few elements.
Also known as
dropLastWhile (Remeda, Ramda) · dropRightWhile (Lodash, es-toolkit, Modern Dash) · ❌ (Radashi, Effect, Antfu)
Example
dropRightWhile([1, 2, 3, 4, 5], (v) => v > 2);
// => [1, 2]
dropRightWhile(
[{ name: 'Alice', active: true }, { name: 'Bob', active: false }],
(u) => !u.active
);
// => [{ name: 'Alice', active: true }]
How it works?
Drops elements from the end while the predicate returns true. Scans from right to left.
Use Cases
Trim trailing empty or whitespace strings 📌
Remove trailing empty or invalid entries from an array. Perfect for cleaning up user inputs, CSV parsing, or form data with trailing blanks.
const inputs = ["Alice", "Bob", "Charlie", "", "", ""];
const cleanedInputs = dropRightWhile(inputs, (val) => val === "");
// => ["Alice", "Bob", "Charlie"]
Remove trailing zeros or placeholder values
Drop trailing numeric placeholders or padding from data arrays. Perfect for trimming sensor data, audio buffers, or fixed-length records.
const audioSamples = [0.5, 0.8, 0.3, 0.1, 0, 0, 0];
const trimmedSamples = dropRightWhile(audioSamples, (val) => val === 0);
// => [0.5, 0.8, 0.3, 0.1]
Exclude recent/future entries from sorted data
Drop trailing elements from a sorted array based on a date or value threshold. Perfect for excluding future-dated records, pending transactions, or draft entries.
const posts = [
{ title: "Post 1", status: "published" },
{ title: "Post 2", status: "published" },
{ title: "Post 3", status: "draft" },
{ title: "Post 4", status: "draft" },
];
const publishedPosts = dropRightWhile(posts, (p) => p.status === "draft");
// => [{ title: "Post 1", status: "published" }, { title: "Post 2", status: "published" }]