Drop While
JS Functions
Easy
10 min
arrays
lodash
higher-order functions
Implement dropWhile(array, predicate). Starting from the beginning of array, it skips elements while predicate returns a truthy value. As soon as the predicate returns a falsy value, that element and everything after it are returned in a new array.
dropWhile([1, 2, 3, 4, 1], (n) => n < 3); // [3, 4, 1]
dropWhile([5, 1, 2], (n) => n < 3); // [5, 1, 2] (first element already fails)
dropWhile([1, 2], (n) => n < 3); // []
const lines = ['', ' ', 'title', '', 'body'];
dropWhile(lines, (line) => line.trim() === ''); // ['title', '', 'body']
Requirements
predicateis called aspredicate(value, index, array).- Stop calling
predicateas soon as it returns a falsy value. Elements after that point are kept even if they would pass (the trailing1above). - Return a new array. Don't mutate the input.
Follow-up
- How does
dropWhilediffer fromfilterwith the negated predicate? - How would you write
takeWhile, its mirror image?
Spotted a mistake or a rights concern? Report an issue