My algorithm below passes on every test except for
dropElements([1, 2, 3, 4], function(n) {return n > 5;});
in which the output is [3, 4]. Could anyone tell me why my algorithm isn’t returning [], but [3,4] instead?
function dropElements(arr, funct) {
for(i=0; i <arr.length; ++i){
if(funct(arr[0]) === false){
arr.shift();
}
else if(funct(arr[0]) === true){
return arr;
}
}
return arr;
}
you are modifying the array in the loop you are iterating. so it drops the first 2 elements and then its at then end of the array and returns. It is seldom do you actually want to delete elements from an array in a loop that you are iterating over.
you are also modifying the array that was passed to you.
try using a temporary array in the function and returning that.
Your algorithm may pass most of the provided tests but there are two critical errors that makes your algorithm incorrect: 1) you are mutating the array while iterating on the same array, 2) you are returning the array as soon as the condition is met.
- you are mutating the array while iterating over the same array.
To see why this is problematic, keep track on variables affected by each iteration.
Iteration #1
arr.length = 4
i = 0
Iteration #2
arr.length = 3
i = 1
Iteration #3
arr.length = 2
i = 2
Based on your loop condition, iteration ends here and returns the array, [3, 4]
- you are returning the array as soon as the condition is met.
Consider following,
// Drop element that doesn't meet the requirement specified by callback function.
dropElements([3, 2, 1], function(n) {
return n > 2;
});
// Expects: [ 3 ]
// Yields: [3, 2, 1]
On first iteration, since 3 is greater than 2, the code flows to return statement in ‘else-if’ clause that will terminate the loop. Hence, your algorithm yields incorrect result, [3, 2, 1].
You should re-think about your approach.
Hi,
I could pass it but I’m afraid that it’s not an ideal code…
function dropElements(arr,func) {
for (var i =0; i<arr.length+i; i++) {
if(func(arr[0]) === false ) {
arr.shift();
} else {
return arr;
}
}
return arr;
}
dropElements([1, 2, 3, 4], function(n) {return n > 5;});