Drop Right WhileLoading saved progress…

Drop Right While

Implement dropRightWhile(array, predicate) — return a new array with the trailing elements removed for as long as predicate returns truthy, scanning from the end. The moment you reach an element where the predicate is falsy, you stop: that element and everything before it are kept. This mirrors Lodash's _.dropRightWhile. It is the right-to-left twin of dropWhile, which trims from the front instead.

Signature

// array:     T[]                                  — the array to trim from the end.
// predicate: (value: T, index: number, array: T[]) => boolean
//            — called on each candidate; truthy means "keep dropping."
// returns:   T[]
//   A NEW array; the trailing run that satisfied the predicate is gone.
function dropRightWhile(array, predicate): T[];

Examples

// The trailing 3 and 4 both pass n > 2, so both are dropped; 2 fails, so it stays.
dropRightWhile([1, 2, 3, 4], (n) => n > 2);
// → [1, 2]
// The last element, 3, already fails n > 5, so nothing is dropped.
dropRightWhile([1, 2, 3], (n) => n > 5);
// → [1, 2, 3]

Notes

  • Only the trailing run. A matching element earlier in the array is kept — you stop at the first element from the right that fails.
  • The predicate gets (value, index, array). The same three arguments JavaScript's array methods pass.
  • All match → empty array. If every element is truthy, dropRightWhile returns [].
  • Empty in, empty out. dropRightWhile([], fn) returns [].
  • Don't mutate the input. Read the array; build and return a fresh one.
Loading editor…