Skip to content

Instantly share code, notes, and snippets.

@nickihastings
Last active March 30, 2018 13:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nickihastings/f5bc47abd9d2e4b9346157f83d7aea6f to your computer and use it in GitHub Desktop.
Save nickihastings/f5bc47abd9d2e4b9346157f83d7aea6f to your computer and use it in GitHub Desktop.
Drop the elements of an array (first argument), starting from the front, until the predicate (second argument) returns true. The second argument, func, is a function you'll use to test the first elements of the array to decide if you should drop it or not. Return the rest of the array, otherwise return an empty array.
function dropElements(arr, func) {
// Drop them elements.
//shift() removes the element if it returns false
//so loop over the array, test against the function
//if it returns false remove the element, otherwise
//return the array.
while(arr.length > 0){
var check = func(arr[0]);
if(!check){
arr.shift();
}
else{
return arr;
}
}
return arr; //returns the array if the loop completes
}
dropElements([1, 2, 3], function(n) {return n < 3; });
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment