4.4. Drop items while a test holds (from either end)
Topics
This question is in
4. Array utilitiesA log file starts with blank lines and comment lines before the real entries. A chat history loaded from the server begins with messages the user has already read. A list of form values ends with empty fields. In each case the unwanted items sit at one end, and the rule is "skip them until the first one that matters", not "remove every match".
Write dropWhile(array, predicate) and dropRightWhile(array, predicate) in dropWhile.js. dropWhile drops items from the start while predicate holds; dropRightWhile drops them from the end. Both return a new array with what is left.
Signature
function dropWhile(array, predicate) // returns a new array
function dropRightWhile(array, predicate) // returns a new arrayarray: the items. It is not changed.predicate(value, index, array): returns a truthy value for an item that should be dropped.- Both return a new array, even when nothing was dropped.
Requirements
dropWhiledrops items from the start whilepredicatereturns a truthy value, and keeps the first item that fails and everything after it, even later items that would match.dropRightWhiledoes the same from the end, and keeps everything up to and including the last item that fails.- When every item matches, the result is
[]; when the first item checked fails, the result is a copy of the whole array. - An empty array gives
[], andpredicateis never called. predicategets the value, its real index in the array, and the array.dropRightWhilechecks from the last index down.predicateis not called again after the first item that fails.- Any truthy or falsy return value counts, not only
trueandfalse. - A hole is checked as
undefined. - The input is not changed, and 100,000 items are handled quickly.
Examples
dropWhile([1, 2, 5, 1, 2], (n) => n < 3); // [5, 1, 2]
dropRightWhile([4, 9, 1, 2], (n) => n < 3); // [4, 9]const lines = ["", "# notes", "start", "", "end"];
dropWhile(lines, (line) => line === "" || line.startsWith("#"));
// ["start", "", "end"]: the blank line in the middle staysdropWhile([1, 2, 3], () => true); // []
dropRightWhile([], () => true); // []Environment
- Plain JavaScript in a browser page; the tests call the globals
dropWhileanddropRightWhilefromdropWhile.js. - Any built-in may be used. The predicate is always a function.
Hints
- Can you find the index where the kept part starts (or ends) first, and copy once after that?
- How does a loop stop at the first item that fails?
The explanation comes with the course
A walkthrough of every line of a solution, the mistakes the tests catch, other ways to write it, and links to the lessons that teach each idea.
- Every line explained
- The mistakes each test catches
- Links to the lessons behind it