Using shift() to remove first element once condition is true

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.

Challenge: Drop it

Link to the challenge:

Hi,
You shifted the element before checking the condition in your loop.
For example:

dropElements([1, 2, 3, 4], function(n) {return n === 2;})

should return [2, 3, 4], but yours return [3, 4] because you shifted 2 out of the array before checking the condition which cause the loop to stop.

Yes, the shift is in the wrong spot but there is also another bug. Add

console.log(x)

at the beginning of the for loop and see what that shows you.

1 Like

@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.

In this solution

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

Can you give a little more explanation about what you are asking here? It’s not quite making sense to me.

on

while (!func(arr[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);
}