function dropElements(arr, func) {
let localArr = [...arr];
for (let item of localArr) {
if (!(func(item))) { //if func(item) returns false, then
localArr.shift() // <-- run this line
} else {
return localArr;//if not, stop the loop
// and return the array
}
}
return localArr;// return the array, in case "if" was ignored
}
Why the function dropElements returns [3] in the following code:
this problem is one of the harder to undersatnd, so don’t feel bad.
you dont need to have localArr as a variable, just use the argument arr as it’s already local and the challenge doesn’t require you not to change it.
the for (...of) loop is dynamic and is a place for bugs for this challenge, the challenge requires you to test the first element of the array as shift() already removes it
var arr = [1, 2, 3, 4, 5]
arr.shift() //removes the '1'
console.log(arr) //[2, 3, 4, 5]
console.log(arr[0]) //2
even a simple for loop with usage of arr[0] (istead of arr[i]) fails because it’s also dynamic, for this declare a variable of length at the start withn the length of the array and use it in your simple for loop and using arr[0] instead of arr[i]
a bit difficult to understand but hope it helps
function dropElements(arr, func) {
var length = arr.length
for (i = 0; i < length; i++) {
//what you already did in the for loop
}
return arr //in case all the if statements were true and
//arr is now empty
}
Thank you very much for the reply, i’ve already solved the problem using Array.prototype.filter() , but the question that i was asking is why the function returns [ 3 ] instead of [] in the code above?
because the for (...of) loop is dynamic and changes to the array length, so it “skips” one iteration at the end, it’s difficult to understand, but point is that you should be static