[Solved] Stuck with Drop it Algorithm Challenge

[Solved] Stuck with Drop it Algorithm Challenge
0

#1

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;
    }

#2

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?


#3

Take a look at the break documentation, to see if it sheds any light on your confusion.


#4

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.


#5

Seems like you understand now. Just one note: A break statement will only break out of the closest loop. For example, if I had a nested loop like below, the break will only affect the inner most for loop.

for (var i = 1; i <= 5; i++) {
  console.log('i = ' + i);
  for (var j = 100; j <= 105; j++) {
    console.log('j = ' + j);
    if (j === 102) {
      break;
    }
  }
}

The above would still allow i to get all the way to 5, but j would never display anything above 102 when the code executes (see below).

i = 1
j = 100
j = 101
j = 102
i = 2
j = 100
j = 101
j = 102
i = 3
j = 100
j = 101
j = 102
i = 4
j = 100
j = 101
j = 102
i = 5
j = 100
j = 101
j = 102


#6

Extremely helpful, thank you!