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