Re-creating the Lodash Library: Implement _.dropWhile() using a while loop

Hey everyone,

I’m stuck on task no. 35 of Re-creating the Lodash Library

I understand the solution using the .findIndex() and .drop() methods

Out of curiosity, I tried to make this work using a while loop, but am not able to understand why my code doesn’t work.

Here is my code:

  dropWhile (array, predicate) {
    i = 0;
    while (predicate(array[i] , i , array)) {
      array.shift();
      i++;
    };
    return array;
  },

Below is what I get on the console. I’m not able to understand where the issue stems from. Can anyone help clarify? Thanks so much!!

Remove the i++

Every time you array.shift() your [1] element becomes the [0] element effectively and your array shrinks by one until the while condition becomes false.

You don’t need to increment anything.

dropWhile (array, predicate) {
    i = 0;
    while (predicate(array[i] , i , array)) {
      array.shift();
    };
    return array;
  },

Because your only really testing the first element you can refactor slighty;

dropWhile (array, predicate) {
    while (predicate(array[0] , 0 , array)) {
      array.shift();
    };
    return array;
  },

That makes sense, of course!

Thanks so much, I was burnt out of ideas and couldn’t figure it out!

You’re not allowed to modify the array, you would be interfering with what that array is used for afterwards, and with the callback function.
The index is not a constant 0, that would be pointless.

For example, this should return an empty array:

_.dropWhile([0,1,2,3,4,5,6], (x, i, a) => a.length > 3)

and this should return [4,5,6]

_.dropWhile([0,1,2,3,4,5,6], (x, i) => i < 4)