Algorithms: Drop It Question

Hi guys!
Re Intermediate Algorithms the ‘Drop It’ exercise…

I came up with a nice, neat (by my newbie-standards) bit of code, starting with a for-loop, including the usual " i < arr.length " instruction. It worked beautifully! EXCEPT for the case [1, 2, 3, 4, ] , func(n) {n > 5} . I couldn’t understand why it failed in that one case.

When I created the var “times = arr.length;”, then substituted “times” for the arr.length in the for-loop, bingo! All tests passed. Can someone tell me why this simple changed made such a telling difference. My original code:

~~

function dropElements(arr, func) {  
  for (var i = 0; i < arr.length; i++) {  
  if (!func(arr[0])) {arr.shift(arr[0]);   
  } else {arr.slice(arr[0]);
   }
 } return arr;
}

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

// console output  [ 3, 4 ]  ~~

Many thanks

PeterL

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

Please use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks are not single quotes.

So you’re in a Danger Zone with this solution because you are modifying an array at the same time that you are iterating over it. This turns your array into a moving target. It’s easy to have logical errors or create infinite loops this way.

Scotty says it's hard

Thank you Ariel. Looks like I drove into a minefield on that one.

V. helpful for future reference.

Regards

PeterL