Drop it exercise + iteration question

Hello FCC community,

Having a hard time understanding the difference between using:

if(func(arr[i])){
  break;
} 

AND

if(func(arr[0])){
  break;
} 

All tests pass if I use the latter; however, only 2 tests pass with the first option. I read both the same. If I am removing the first item (arr[0]) in the arr, then second item becomes the first one, no? Hence arr[i] is always arr[0]. What am i not seeing?

As always, thanks for your help!


function dropElements(arr, func) {
/* //option 1-- 
  while(arr.length > 0 && !func(arr[0])){
    arr.shift();
  }
*/
  let arrLen = arr.length;
  for (let i = 0; i <arrLen; i++){
      if(func(arr[i])){
            break;
       } 
      else {
             arr.shift();
       }
   }

 return arr;
}

console.log(dropElements([1, 2, 3], function(n) {return n < 3; }));
  **Your browser information:**

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.55 Safari/537.36

Challenge: Drop it

Link to the challenge:

The problem is that you are mutating the array as you iterate over it, which can produce confusing behavior. I generally recommend that you don’t change arrays as you iterate over them.

Thanks. I’m not sure i quite get it. I tried using slice as to create a copy of the array, but i run into the same issue.

If you are modifying the copy of the array, you still have the same problem.

In the code in your first post, you keep removing the first item, so your array gets shorter and shorter and the element at the first index keeps changing.

Another approach is to find the right index and copy all elements at and past that index.

1 Like

Thanks much! It makes sense. thanks !

1 Like