I don’t understand why this code is not working.
Its giving me this
[2,3,4]
when I run this:
function dropElements(arr, func) {
// Drop them elements.
// console.log(arr.length);
for(var i=0;i<arr.length;i++){
if(func(arr[i])){
break;}
else{arr.shift();}
}
return arr;
}
dropElements([1, 2, 3,4], function(n) {return n >= 3; })
The expected output is [3,4]
I cleaned up your code.
You need to use triple backticks to post code to the forum.
See this post for details.
1 Like
Think about what this line of code is doing:
if(func(arr[i])){
so the first time through it is checking arr[0] which is the number 1. This is not true so the arr is shifted. The next time through it checks arr[1] which since the array has been shifted is now the number 3 ([2,3,4]). This evals to true and returns the arr.
You are making a logical error that is very common among new coders. You are modifying the array that you are iterating over. Because you shift()
the array in your else
block, all the indices shift by one. This means that on the next iteration of the loop, when i
has been increased by 1, a value is skipped over. Run the code below to see what I mean.
1 Like
Thanks very much, just a silly mistake
As a rule of thumb, you don’t want to mutate a collection that you’re iterating over. It can cause this kind of error or, much worse, infinite loops.
1 Like
Will keep that in mind for sure.
