Skip to content

Instantly share code, notes, and snippets.

@eday69
Last active October 8, 2022 17:21
Show Gist options
  • Save eday69/aac7244be6686f25b577a295298b5d6e to your computer and use it in GitHub Desktop.
Save eday69/aac7244be6686f25b577a295298b5d6e to your computer and use it in GitHub Desktop.
freeCodeCamp Intermediate Algorithm Scripting: Drop it
// Given the array arr, iterate through and remove each element
// starting from the first element (the 0 index) until the function
// func returns true when the iterated element is passed through it.
// Then return the rest of the array once the condition is satisfied,
// otherwise, arr should be returned as an empty array.
// Cannot use filter, since we need to return the rest of the array
// once the condition is met. We use a 'For' loop !
function dropElements(arr, func) {
// Drop them elements.
let myArr=[];
for (let i=0; i<arr.length; i++) {
if (func(arr[i])) {
myArr=arr.slice(i);
break;
}
}
return myArr;
}
dropElements([1, 2, 3], function(n) {return n < 3; }); // [1,2]
dropElements([1, 2, 3, 4], function(n) {return n >= 3;}) // [3,4]
dropElements([0, 1, 0, 1], function(n) {return n === 1;}); // [1, 0, 1]
dropElements([1, 2, 3], function(n) {return n > 0;}); // [1, 2, 3]
dropElements([1, 2, 3, 4], function(n) {return n > 5;}); // []
dropElements([1, 2, 3, 7, 4], function(n) {return n > 3;}); // [7, 4]
dropElements([1, 2, 3, 9, 2], function(n) {return n > 2;}); // [3, 9, 2]
@MahdiRezaeiDev
Copy link

function dropElements(arr, func) {
  let index;
  for (let count in arr) {
    if (func(arr[count])) {
      index = count;
      break;
    }
  }

  return index ? arr.slice(index) : [];
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment