The thing is that my first instict was to use shift() like this:
function dropElements(arr, func) {
for (let element of arr) {
if (!func(element)) {
arr.shift();
console.log(arr)
}
else {
return arr;
}
}
return arr;
}
//dropElements([1, 2, 3, 4], function(n) {return n >= 3;})
dropElements([1, 2, 3, 4], function(n) {return n >= 4;})
However, if you try the two examples at the end and see the console.log, you’ll see that there’s always an element that should have been “shifted” but isn’t:
For the first example, the returned array is [2, 3, 4]
For the second example, it’s [3, 4].
So it feels like the loop would need to execute one more time but doesn’t.
I solved the exercise with slice, but still bothers me not knowing why shift doesn’t work (the rest of the code with slice is the same except arr = arr.slice(1) instead of the shift() line).
function dropElements(arr, func) {
// Cannot loop array as the arr is changing, first element is dropped
// The element to check is always the first element
while (!func(arr[0])) {
arr.shift(); // remove first element
}
return arr;
}
console.log(dropElements([1, 2, 3, 4], function(n) {return n >= 3; }));
That’s what I thought at first, but on the second example ( return n >= 4) it removes both the 1 and the 2, but then not the 3, which is what threw me off…