Why does this not work?
Your code so far
function dropElements(arr, func) {
for (let i=0;i<=arr.length;i++)
if(func(arr)=== true){
return arr
} else {
arr.splice(arr[i])
dropElements;
}
}
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/112.0.0.0 Safari/537.36
Challenge: Intermediate Algorithm Scripting - Drop it
Link to the challenge:
Changing the array as you iterate over it produces confusing results. You shouldn’t do that.
Also, I don’t understand why you have that line with dropElements
? I’m not sure what its doing?
I also recommend using more standard formatting so it’s easier to understand the logical flow of your code.
function dropElements(arr, func) {
for (let i = 0; i <= arr.length; i++) {
if (func(arr) === true) {
return arr;
} else {
arr.splice(arr[i]);
dropElements;
}
}
}
the drop elements line is meant to be an example of recursion, so if it doesnt work then it goes back and tries the function again.
I don’t really understand what you mean by not changing the array as iitterate over it
But you aren’t calling the function, so that line doesn’t do anything.
Look at this code:
const testArray = [1, 2, 3, 4, 5];
for (let i = 0; i < testArray.length; i++) {
console.log("i:", i);
console.log("array before splice:", testArray);
testArray.splice(i);
console.log("array after splice:", testArray);
}
What do you see in the console when you run this code?
Or this version:
const testArray = [1, 2, 3, 4, 5];
for (let i = 0; i < testArray.length; i++) {
console.log("i:", i);
console.log("array before splice:", testArray);
testArray.splice(i, 1);
console.log("array after splice:", testArray);
}
I’d just skip splice
altogether here.