Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Javascript filter function

I am having difficulties fully grasping the filter fn in JS.

I have this code;

function destroyer(arr) {
  // Remove all the values
  var args = Array.prototype.slice.call(arguments);
  //console.log(args[2]);
  //console.log(arr);

  function seekAndDestroy(val,index,ar){

    for(var i = 1; i< args.length;i++){
        console.log(args[i]);
    }

  }

  var result = arr.filter(seekAndDestroy);
  //console.log(result);

}

destroyer([1, 2, 3, 1, 2, 3], 2, 3);

This will give the result

2
3
2
3
2
3
2
3
2
3
2
3

My question here is why does it print it out six time, surely it should only count to args.length which is two

1 Answer

There is no need to loop through anything. The filter method does that for you.

All you really need to give the filter function is another function that returns a boolean, which determines wether or not the value will be filtered out.

function onlyEvenNumbers(number) {
    return number % 2 == 0;
}


var result = [1, 2, 3, 4, 5, 6].filter(onlyEvenNumbers);
console.log(result); // prints out [2, 4, 6]

Here is a simplified version of a filter function:

Array.prototype.customFilter = function(callback) {
    var result = [];
    for (var i = 0; i < this.length; i++) {
        if(callback(this[i])) {
            result.push(this[i]);
        }
    }

    return result;
}

function onlyEvenNumbers(number) {
    return number % 2 == 0;
}


var result = [1, 2, 3, 4, 5, 6].customFilter(onlyEvenNumbers);
console.log(result); //Still prints out [2, 4, 6]

thanks for the answer, I mostly understand it now, but how does it work if returning boolean expressions such as true or false?

actually don't worry got it now! thanks