Re-creating the Lodash Library: _.dropWhile using if...for. Code works but not sure why!

Hi there!

I’m on the lodash library project, the dropwhile section, and while I’ve gotten my code to work, I don’t quite understand why it’s working…

I didn’t use the findIndex method, instead using a for…if loop. The if loop checks for a truthy response from the predicate function, then uses shift to remove the first element… when it gets a falsy response from the predicate, the function stops and returns the array as it is at that point.

CODE:

    dropWhile(array, predicate) {
    for (let i = 0; i < array.length; i++) {
      if (predicate(array[i], i, array)) {
        array.shift()
      } else {
        array.shift();
        return array;
      }
    }
  },

The error states:

Failed: _.dropWhile([1, 2, 0, 4], indexIsSmallerThanElement returned [ 2, 0, 4 ] instead of [ 0, 4 ].

If I amend the code to remove an additional element from the front of the array (commented out in the code above) it passes the tests but I don’t understand why. Isn’t the extra element that is being removed the one that has generated a false response so should be left on the array being returned - or have I not understood the requirement?

Maybe I just can’t see the wood for the trees on this one! Any help would be appreciated :slight_smile:

You must select a tag to post in this category. Please find the tag relating to the section of the course you are on E.g. loops, learn-compatibility

When you ask a question, don’t forget to include a link to the exercise or project you’re dealing with!

If you want to have the best chances of getting a useful answer quickly, make sure you follow our guidelines about how to ask a good question. That way you’ll be helping everyone – helping people to answer your question and helping others who are stuck to find the question and answer! :slight_smile:

all you’re showing is that the test doesn’t work

Just realised I forgot to comment out the fix in the code.

So the code that doesn’t pass the test:

dropWhile(array, predicate) {
    for (let i = 0; i < array.length; i++) {
      if (predicate(array[i], i, array)) {
        array.shift()
      } else {
//        array.shift();
        return array;
      }
    }
  },

And the code that does:

dropWhile(array, predicate) {
    for (let i = 0; i < array.length; i++) {
      if (predicate(array[i], i, array)) {
        array.shift()
      } else {
        array.shift();
        return array;
      }
    }
  },