Intermediate algorithm DROP IT solution

Intermediate algorithm DROP IT solution
0

#1

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


#2

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 ]


#3

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]’.


#4

In the test case you reference above, the first element is 1. Since 1 >= 3 is NOT true, then it gets dropped. The second element is 2. Since 2 >= 3 is NOT true, then it gets dropped. The third element is 3. Since 3 >= 3 is true, we stop dropping any more elements and return the array [3, 4].