Skip to main content

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