Need help with "Drop It" task

Need help with "Drop It" task
0

#1

Tell us what’s happening:
I am struggling to understand why my code is giving me the last 2 elements of the array if no elements in the array meet the critera of the function. for instance this spectific example returns [0,4]. Am i doing something wrong? Also I do not understand why I need the second “return arr;” but if I do not have it in my code, dropElements([1, 2, 3, 4], function(n) {return n >= 3;}) returns nothing. I am very confused.

Your code so far

function dropElements(arr, func) {
  // Drop them elements.
  for(i=0;i<arr.length;i++){
    if(func(arr[0])==false){
      arr.shift();
    }
    else{
      return arr;
    }
  }
  return arr;
}

dropElements([1, 2, 0, 4], function(n) {return n > 7;});

Your browser information:

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

Link to the challenge:


#2

firstly…
it is common to avoid modifying an array you are looping with.
What i mean by that is…

// you are looping by the reference of arr.length here
for(i=0;i<arr.length;i++){
  ...
  // you modified the array somewhere inside the loop
  arr.shift() // this will make the loop unstable and unpredictable.
  ...

Now i am going step through how operations are called from the code you posted when the program is running.

//[S0] : first call to the function
dropElements([1, 2, 0, 4], function(n) {return n > 7;});

//[S1] : 'i' is 0 and 'arr.length' is 4 here
for(i=0;i<arr.length;i++)


//[S2] : the statement below will return true
// arr[0] is 1 and calling func(1) will result false.
if(func(arr[0])==false)

//[S3] : the program will shift the arr now.
// arr will become [2,0,4]
arr.shift()

//[S4] : the program finished the first loop and rechecking the condition
// i is 1 and arr.length is 3 now 
// the loop decided to continue because 1 > 3 is false
// arr[0] is 2 and func arr[0] will be false. 
// if condition will return true here.
if(func(arr[0])==false)

//[S5] : the program will shift the arr now.
// arr will become [0,4]
arr.shift()

//[S6] : the program finished the second loop and rechecking the condition
// i is 2 and arr.length is 2 now and,
// the loop decided not to continue because 2 > 2 is false
// the program decided to end the loop and return the arr.
// this is the outer loop return
return arr;

// this is how the code returning [0,4] because arr is [0,4]

hope this program steps helps.


#3

This helps so much. i just assumed that the arr.length function would be costant since it is a parameter of the for loop. I didnt realize that it would also change with the array. After setting the length to a variable before the for loop the code passed. Thanks for the help!