Intermediate Algorithm Scripting: Drop it

Tell us what’s happening:
Not sure why my code isn’t working. Seems right to me: create a for loop to iterate through the array, when the first element passes the function, return the remaining array. Otherwise, if the element doesn’t pass the function, remove it from the array and test the next element in the array.

Your code so far


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

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/70.0.3538.102 Safari/537.36.

Link to the challenge:

shift doesn’t need arguments :slight_smile:

However that’s not the point: you’re using the same array on which you operate^^

Let’s say you have myArr=["one", "two", "three"];
You iterate through it with a simple for loop :

for (let i=0; i<myArr.length; i++) {
console.log(myArr[i])
}

first loop ;

myArr=["one", "two", "three"]
myArr[0] // "one"

second loop ;

myArr=["one", "two", "three"]
myArr[1] // "two"

third loop ;

myArr=["one", "two", "three"]
myArr[2] // "three"

Now, add a shift operation on the same array:

for (let i=0; i<myArr.length; i++) {
console.log(myArr[i])
arr.shift();
}

first loop ;

myArr=["one", "two", "three"]
myArr[0] // "one"

second loop ;

myArr=[ "two", "three"]
myArr[1] // "three"

You see that? :wink:
The ‘check logic’ can be considered correct, however you may want to test it on a copy of the array and trace the index so you can at the end return the correct ‘slice’ of the original arr ^^

Ah, I see my mistake now. I changed my code to replace arr[i] with arr[0] so that the loop doesn’t skip an element once the previous element is removed from the array. But my code still isn’t passing this lesson - it passes all except for the one where it’s suppose to return an empty array. What am I doing wrong? My code now looks like this:

function dropElements(arr, func) {

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

return arr;
}

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

The error is the same as before, you’re using ‘limits’ derived from a ‘variable item’

for (var i = 0; i < arr.length; i ++) {

You can collect the arr length before to manipulate it and then use it:

let arrLngt = arr.length
for (var i = 0; i < arrLngt; i ++) {