Tell us what’s happening:
Why isn’t this working? When func is true the loop is supossed to stop and return the arr but I can’t get it to work in all the tests
Your code so far
function dropElements(arr, func) {
for (let x of arr){
arr.shift()
if (func(x)){
break
}
}
return arr
}
let z = dropElements([1, 2, 3, 4], function(n) {return n >= 3;})
console.log(z)
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:82.0) Gecko/20100101 Firefox/82.0.
@bbsmooth Yes, thanks you for pointing that out. The problem is the length of the array is changed during the loop. Should have use the while loop instead.
function dropElements(arr, func) {
while (!func(arr[0])) {
console.log(arr[0])
arr.shift();
}
return arr;
}
// test here
let x = dropElements([1, 2, 3, 4], function(n) {
return n >= 3;
});
//console.log(x)
why does arr[0] keeps incrementing? I would expect it to just keep being 0
I would expect the while loop always to check if func(arr[0]) equals to false, but instead you get [0] in the first iteration, then [1], [2], etc but there is not code for it to increment
OK, I think you are asking why arr[0] is a different value each time through the loop. Let me ask you this, what are you doing to arr each time through the loop?
Think about @bbsmooth question first, I’m sure you can find the answer. What are you doing to the array inside the while loop after logging?
arr.shift() is changing the array so the first element is different each iteration.
const array = [1, 2, 3, 4, 5];
for (let index = 0; index < array.length; index++) {
console.log('Element at index 0: ', array[0]);
console.log('Element returned from shift: ', array.shift());
console.log('Array after shift: ', array);
}