5

I was posed a question during an interview that has left me scratching my head. Rather than spend the weekend worrying about the results, I wanted to try to solve the problem, but I can't figure it out:

Using the below reduce function, build a filter function that takes an array and a test function as arguments, and returns a new array that has filtered the elements of the previous array based on the test function.

This would be simple with using forEach or similar but the requirements were to use this reduce function:

function reduce(array, combine, start) {
  var current = start;
  for (var i = 0; i < array.length; i++)
    current = combine(current, array[i]);
  return current;
}

So

var myArray = [0, 1, 3, 5, 9];
console.log(filter(myArray,function(x){
 return x > 2; 
}));

would return

[3,5,9]

I tried the below but I'm getting an illegal return statement and I'm not even sure I'm going down the right path here.

function filter(array, test){
 var giveArray = [];
  if(reduce(array,function(current,start){
    return test(current);
  },false)){
    giveArray.push(current);  
  }
 } 
  return giveArray;
}
1
  • Not allowed to use Array.prototype.filter? function bigEnough(x) { return x > 2; }; / var myArray = [0, 1, 3, 5, 9]; / console.log( myArray.filter(bigEnough) ) of course you can inline anonymous instead of declaring bigEnough function. Commented Jan 22, 2016 at 19:53

1 Answer 1

9

The basic idea is you use the combine function passed to reduce as a means of filtering elements. Your approach seems to imply that reduce should return a boolean value but that's not what it's for. Use test for the conditional check and reduce will be used to fill up the array with the passing elements.

function filter(array, test) {
  return reduce(array, function(arr, el) {
    // Only add to the array if the test function is true
    if (test(el)) {
      arr.push(el);
    }

    // Always return the same array so you can keep filling it
    return arr;
  }, []); // Give it an empty array to start with
}
Sign up to request clarification or add additional context in comments.

Comments

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.