Drop it - Why doesn't my filter return pass all tests?

Drop it - Why doesn't my filter return pass all tests?
0.0 0

#1

Tell us what’s happening:
I created a simple filter to remove all the elements in the arr that don’t evaluate to true when passed through the provided function. There are two tests that won’t pass and I can’t figure out why…

Your code so far


/* jshint esversion: 6 */ 
function dropElements(arr, func) {
  // Drop them elements.
  var output = arr.filter((val) => {
      if (func(val)) {
        return true;
      }
     return false;
  });
  return output;
}

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

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36.

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


#2

What do the failing tests say?


#3

Review the spec for Array.filter:

(when the function returns true, that means KEEP the element)

Also, a simple filter is not what the linked challenge is asking for… it’s asking to return a slice of the array, starting at the first element for which the func returns true, ending at the end of arr…


#4

The challenge requirements are sightly different than a filter out what we don't want.

It’s more of a: iterate and remove element that are false for the callback. As soon as you encounter the first that is true exit the loop and keep all the rest.

In fact look at this test case:

dropElements([0, 1, 0, 1], function(n) {return n === 1;}) 
should return [1, 0, 1]

As you can see it’s not filtering out the middle 0 even tho it’s false for the function provided.


#5

Thanks for that tip. I’ll take a closer look and solve it with this in mind.


#6

Ok so I think I got it but why isn’t second ‘else if’ returning an empty array?

It’s hitting all other solutions correct except the arr I’m settign to “[]” if func(arr[i]) returns undefined:

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

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

}
 return arr;
}

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

#7

Ok, got it. Was making this too complex. Final solution:

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

while (!func(arr[0])) {
  arr.shift();
}
return arr;
}
dropElements([1, 2, 3], function(n) {return n < 3; });