This is my solution to Drop It.
It passes all but 1 of the tests. It fails the forth test, by returing undefined instead of the required empty array:
Given my method uses .shift() in a similar way to solution 1 of the FCC solutions, I can’t work out why my method results in an undefined array instead of an empty one.
Your code so far
function dropElements(arr, func) {
let arrCopy = [...arr]
for (let i = 0;i<=arrCopy.length;i++){
if (func(arrCopy[i]) == true) {return arr}
else {arr.shift()}
}
}
dropElements([1, 2, 3], function(n) {return n < 3; });
Your browser information:
User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36
I’ve applied your ideas but am in the same situation. The code works until the case where the array is emptied, in which case it returns “undefined” instead of “”.
My new attempt:
function dropElements(arr, func) {
let arrCopy = […arr]
for (let i = 0;i<=arr.length;i++){
if (func(arr[i])) {return arrCopy}
else {arrCopy = arr.slice(i+1)}
}
}
dropElements([1, 2, 3], function(n) {return n < 3; });
I suppose my real question is why does the below solution work, and mine not, when the implementation of shift looks the same to me?
function dropElements(arr, func) {
while (arr.length > 0 && !func(arr[0])) {
arr.shift();
}
return arr;
}
// test here
dropElements([1, 2, 3, 4], function(n) {
return n >= 3;
});
Leave “arr” completely out of the loop, You only work with the new array arrCopy, This is also the only thing to return if the array has a length of > 0. Or simpler: You only need to return one line in the if code block. You also don’t need to add anything to i in slice().
Since there are only two options no else needed, simply return an empty array in case the if condition isn’t met. Watch out to put this return statement in the right scope.