Drop it: solved but not sure how(?!)

Drop it: solved but not sure how(?!)
0

#1

So I solved this challenge but there’s something in my code that I don’t understand why/how it’s working(!). The idea is to loop through the array until I find ‘first’ i.e. the first occurrence where func returns true and then use this to slice the array or return an empty array if the func returns -1.

What I don’t get is how the index of the first value that makes the function return true is transposed from inside the while loop to the first variable underneath. I didn’t store it inside the while loop to call it afterwards (and even if I did, after the break; statement it would be unreachable right?).

In other words how can arr.indexOf(arr[i]) be the specific index that made the loop stop? Couldn’t it be any index of any value inside the array?

Does this make sense?

Thanks

Your code so far

  var i=0;
  while(i<arr.length){
    if(func(arr[i])){
      break;
    }
    i++;
  }
  var first = arr.indexOf(arr[i]);
  return first===-1?[]:arr.slice(first);
}

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

Your browser information:

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

Link to the challenge:


#2

Because i is tracking the current index of arr before the break is executed. When func returns true, the while loop breaks and i has the index of arr where you should slice. In fact, since i already contains correct index where the slice should start, you could simplify your code and start i at -1 and not have to use indexOf.

function dropElements(arr,func) {
  var i=-1;
  while(i<arr.length){
    if(func(arr[i])){
      break;
    }
    i++;
  }
  return i===-1?[]:arr.slice(i);
}

#3

cool!

so each time the loop runs, i is updated outside the loop.
when func turns true, i is already stored and can be used straight away in the last line of code that returns the desired part of the array.

Thanks very much!