Drop WhileLoading saved progress…

Drop While

Implement dropWhile(array, predicate). It returns a new array with the leading elements removed for as long as predicate returns truthy. The moment the predicate returns a falsy value, dropping stops: that element and everything after it are kept, even if some of those later elements would have satisfied the predicate. This mirrors Lodash's _.dropWhile.

Signature

// array:     T[]                                   — the array to read from.
// predicate: (value: T, index: number, arr: T[])   — called with each element,
//                                                     its index, and the array.
// returns:   T[]
//   A NEW array starting at the first element for which the predicate is falsy.
function dropWhile(array, predicate): T[];

Examples

// Drop the leading run of values below 3.
dropWhile([1, 2, 3, 4], (n) => n < 3);
// → [3, 4]
// The first element already fails the predicate, so nothing is dropped.
dropWhile([1, 2, 3], (n) => n > 5);
// → [1, 2, 3]

Notes

  • Only the leading run is dropped. Dropping stops at the first falsy result. A later element that would satisfy the predicate is kept — dropWhile([1, 2, 3, 1], (n) => n < 3) returns [3, 1], not [3].
  • The predicate gets three arguments. It is called as predicate(value, index, array), just like the callback for Array.prototype.filter.
  • All-truthy drops everything. If the predicate never returns falsy, the result is [].
  • Empty in, empty out. dropWhile([], fn) returns [].
  • Do not mutate the input. Read the array; return a fresh one.
Loading editor…