0

In a functional programming exercise I found online, the instructions are as follows:

"Implement JavaScript’s native ‘filter’ method that takes two arguments (a collection and a test function that returns either a ‘true’ or a ‘false’) and iterates over the collection using the ‘each’ function you wrote earlier and returns the resultant array."

I've already completed the first part of the exercise and created a function that implements JS' forEach method:

var each = function(collection, iterator) {
  if(Array.isArray(collection)){
   for(var i = 0; i < collection.length; i++){
  // value, key/property, collection
    iterator(collection[i],i,collection);
  }
  } else if (typeof collection === "object"){
    for(var property in collection){
      iterator(collection[property], property, collection);
    }

   }else{
     console.log("you messed up!");
  }
 };

Test my function with:

function returnOdds(currentEl) {
   return currentEl % 2 !== 0;
}
 console.log(filter([1, 2, 3], returnOdds)); // output: 1, 3

I'm not sure how to call my 'each' function on the 'collection' parameter inside my filter function.

Is this legal to do?

function filter(collection, test) {
   each(collection);

}

Or perhaps I can call the 'test' parameter as a function that checks to see if collection[i] is not an even/odd number?

function filter(collection, test) {
   var odd = function(each()){
    each(collection){
       if(collection[i] !== 0){
            return odd;
          }
         }
       }
    }

I am wondering if any of this even makes sense or can be done.

0

1 Answer 1

1

The filter() function that you are being asked to implement needs to somehow build up a new array of values that pass the test, and then return that new array. Here's one way to do it that uses your existing each() method:

var filter = function(collection, test) {
  var results = [];
  each(collection, function(val) {
    if (test(val)) {
      results.push(val);
    }
  });
  return results;
};

You can then call this function in the way you showed in the middle of your question, passing in an array and a reference to some other function that will return true or false for a given item:

var oddNumbers = filter([1, 2, 3], returnOdds);

Demo: https://jsfiddle.net/4rj7phot/

So this works as follows:

  1. Create an empty array for the results.
  2. Use your each() function to execute an anonymous function for each item in the collection argument.
  3. Within the anonymous function, call the function provided in the test argument, passing the current item value, and if that function returns true (or a truthy value) add the item to the results array.
  4. Return the results.

I'll leave any validation of the arguments (e.g., checking that test actually is a function) to you.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for the help! I'm still a bit confused on what the "val" argument does in the anon function. Particularly I don't quite understand what you mean by "call the function provided in the test() argument".
Sounds like you need to take a step back from the filter() implementation and just work on some simpler examples calling your own each() function by itself to do some simple array iteration. For example, trying using each() to print out all of the values in a given array. (Perhaps use console.log() to "print".)
Your each() takes two arguments, the first being the array that it will loop over, the second being a callback function that it will call for each element - when each calls that function it passes the value of the current item in the first argument: that's what the line iterator(collection[i],i,collection); does in your function. (It also passes some other arguments, but my code ignores them.) So in my code, the anonymous function is the iterator() being called, and val is the argument that receives the value of the current element.
All of this type of code relies on the fact that in JS functions are a type of object, and when you call function a you can pass a reference to function b as an argument such that function a can then call b().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.