[Solved] Stuck with Drop it Algorithm Challenge

Hello guys,

I have written the following code:

function dropElements(arr, func) {
  var newArray = arr.filter(func);
 return newArray;  
}

So the problem here is, that I don’t pass the following tests:

dropElements([0, 1, 0, 1], function(n) {return n === 1;}) should return [1, 0, 1]
dropElements([1, 2, 3, 9, 2], function(n) {return n > 2;}) should return [3, 9, 2]

I understand what needs to be done. If the first item is found which gives back true, the script should stop and return the rest of the array ( so the script should stop checking the other indexes, maybe a break will do the job?)

Thank you for your help!

Update 1:
So after struggling a little bit with this, I found the solution with slice():

    function dropElements(arr, func) {
      var newArray = [];
      for(var i = 0; i < arr.length; i++){
        if(func(arr[i])){
         newArray = arr.slice(i);
         break;
        }
      }
      return newArray;
    }
1 Like

Hi, I know this topic is old but I was wondering why the solution does not work without break. What does break do in this problem? Explain like I’m five.

Input: dropElements([1, 2, 3], function(n) {return n < 3;});

Output with break: [1, 2, 3]

Output without break: [2, 3]

Why is this?

So… with break it returns [1, 2, 3] because it breaks out of the for loop and instantly returns newArray when it sees 1 < 3.

But without break, it keeps iterating until it hits the last element of the array. Returns [2, 3] and not [3] because 3 is not less than 3, so it doesn’t slice at that index. Only at the number 2.

Correct? Makes sense now.

Extremely helpful, thank you!