Question about 'Drop It' Exercise

Hi all,

There’s something that has been bothering me about the exercise ‘Drop It’ since the other day when I did it. For reference, the exercise is here: https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/drop-it

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

Does anybody know?

Thanks!

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; }));

1 Like

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… :face_with_raised_eyebrow:

Hint: Place a console.log(element) right before the arr.shift() to see what it does.

I just finished my own “drop it” this morning. Took me a few tries, but my final solution looks simple…^^

Hmmm interesting… That was not how I was expecting the loop and the if statement to behave with the array and shift… That’s odd!

You cannot loop something that is changing. That is why I used a while statement as in my example.

1 Like

I used filter and had a help in stackoverflow to make it work! :slight_smile:

function dropElements(arr, func) {  
return arr.filter((b => v => b ||= func(v))(false));;
}