Intermediate algorithm DROP IT solution

Continuing the discussion from freeCodeCamp Algorithm Challenge Guide: Drop It:

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

// test here
dropElements([1, 2, 3, 4], function(n) {return n >= 3;})

So I came up with same solution as above, but in my for loop I just wrote in as follows :
(var i = 0; i < arr.length; i++)
I did not create variable times = arr.length. My solution was working but would never work for this input: dropElements([1, 2, 3, 4], function(n) {return n > 5;}) should return [].

Finally I gave up and looked at solution. Can anyone explain why it works when create var that is defined exactly as arr.length, but does not work when I write in arr.length? is it not the same thing ( im still learning)

Thanks a lot

1 Like

It’s because length of arr changes with every iteration and it will iterate only first arr.length / 2 elements of array.
In your case loop will stop after 1, 2 and returns [ 3, 4 ]

Hello, is there a some contradiction in the first part of description of challenge:
Drop the elements of an array (first argument), starting from the front, until the predicate (second argument) returns true ?

But, looks like the test needs the return of the function is to be false.
For example: ‘dropElements([1, 2, 3, 4], function(n) {return n >= 3;}) should return [3, 4]’.

This is my solution using reduce method

function dropElements(arr, func) {
  //use reduce method to loop through the array with an array as a return value
  let answer = arr.reduce((result, current) => {
    //check if the function is true for the current item in the array
    if(func(current)){
      //if true splice the original array and pass it on to the result 
      result = arr.splice(arr.indexOf(current))
    }
    return result;
  }, [])
  return answer;
}

It is great that you solved the challenge, but instead of posting your full working solution, it is best to stay focused on answering the original poster’s question(s) and help guide them with hints and suggestions to solve their own issues with the challenge.

We are trying to cut back on the number of spoiler solutions found on the forum and instead focus on helping other campers with their questions and definitely not posting full working solutions.

Thank you for understanding.

1 Like

I made a very clean (imo) and simple code:

function dropElements(arr, func) {
let arrCopy = […arr];
for (let a = 0; a = arrCopy.length; a++) {
if (!func(arrCopy[0])) {
arrCopy.shift();
}
}
return arrCopy;
}
dropElements([1, 2, 3, 4], function(n) {return n > 5;});