Intermediate Algorithm Scripting: Drop it_Is there a bug?

Hi there. Wondering if there’s a bug in this challenge.

https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/intermediate-algorithm-scripting/drop-it

I’m unable to pass the fourth test with

function dropElements(arr, func) {
  // Drop them elements.
  
  for (let i = 0; i<arr.length; i++) {
    if (func(arr[0])===true) {
      break;
    } else {
      arr.shift();
    }
  }
  return arr;
}

dropElements([1, 2, 3], function(n) {return n < 3; });

Aren’t you testing the same element each time? Why do you need i if you don’t use it?

Ah, I get it now. I realize I’m supposed to first pass the length of arr to a variable in order to preserve it (keep it the same length). We need ‘i’ to iterate through the array. We don’t need i in the body of the for-loop though because arr.shift() pops off the first element of the array with each iteration.

1 Like

You are missing a variable instead of let.

function dropElements(arr, func) {
// Drop them elements.

for (var i = 0; i<arr.length; i++) {
if (func(arr[0])===true) {
break;
} else {
arr.shift();
}
}
return arr;
}

dropElements([1, 2, 3], function(n) {return n < 3; });

People get so fixated on for loops. Sometimes while is the right tool for the job.

function dropElements(arr, func) {
  // Drop them elements.
  while(!func(arr[0])){
    arr.shift();
  }
  return arr;
}
1 Like

for me this code is working fine

function dropElements(arr, func) {
    // Drop them elements.
    let i = 0;
    let _arr = [...arr];
    for (i; i < _arr.length; i++) {
        let result = func(_arr[i]);
        if (result) {
            return arr;
        } else {
            arr.splice(0, 1);
        }
    }
    return [];
}

dropElements([1, 2, 3], function (n) { return n > 0; })