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:
https://www.freecodecamp.org/challenges/drop-it