Intermediate Algorithm Scripting - Drop it

Tell us what’s happening:

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

Challenge Information:

Intermediate Algorithm Scripting - Drop it

Hello!

Here are some thoughts:

If you still can’t solve, feel free to post your modified code! Happy hacking.

Thank you Daniel
Appreciate the engagement

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

don’t look at arr.shift, look at the call to the callback function, try to understand how the two differ

You are already on the right path.

  • 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.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.