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" }]