Last active
October 8, 2022 17:21
-
-
Save eday69/aac7244be6686f25b577a295298b5d6e to your computer and use it in GitHub Desktop.
freeCodeCamp Intermediate Algorithm Scripting: Drop it
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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
commented
Oct 8, 2022
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment