Iterating through array, code not working as intended

Tell us what’s happening:
I’m doing this challenge linked below.
When second element of array goes through loop it does not shift out of the array and I don’t understand why.
when n>=4 it does shift, but the third one does not.

Your code so far


function dropElements(arr, func) {
  let changed = false;
  for(let el of arr) {
    //console.log(arr);
    if(!func(el)) {
      //console.log("shifted");
      arr.shift();
      changed = true;
    } else if(changed) return arr;
  }
  return arr;
}

console.log(dropElements([1, 2, 3], function(n) {return n >= 3;}));

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/drop-it

At a guess, because you’re both iterating over arr and editing it as you go, it’s causing problems. It would be like doing the same code with a regular for loop, but removing array members, so the last few passes are throwing errors regarding invalid indexes.

Instead, you may want to consider a do...while looping mechanism. Read about it on devdocs.

The logic to it might be:

  • set a true/false flag, for example let stopNow=false
  • start the do/while loop
    • Is the first element of the array to be removed?
      • if yes, remove it.
      • if no, it’s time to stop the loop and exit - set our flag to true
  • end the do/while loop with some condition that checks our flag.
  • at this point, we’ve either got a good array, or an empty one. Toss it back!
1 Like

Right! Didn’t think about it, thanks a lot!!

1 Like