6

How can one pass a variable to a filter function in javascript?

In this case I'm trying to pass a value to variable "maxage":

var dateFilter = function(value,maxage) { // Age in miliseconds
    if(Date.now() - value < maxage) {
        return value;
        } else {
        return false;
        }
    }

    dates.filter(dateFilter,500);

How can I pass the value 500 to the filter as maxage?

1
  • I'm trying to pass 500 to the filter as variable maxage Commented Dec 7, 2012 at 1:50

3 Answers 3

13

You would need to invoke Function.prototype.bind to create something similar to a default argument.

dates.filter(dateFilter.bind( null, 500 ));

dateFilter callback would then called with 500 PLUS "automatic passed in values" value, index, array.

function dateFilter( customArgument, value, index, array ) {
    // customArgument === 500
}
Sign up to request clarification or add additional context in comments.

3 Comments

You have it turned around. The bound argument is first, and the others are passed after. Like this: function dateFilter( customArgument, value, index, array ) {
@IHateLazy: did I say nope ? O_o
I didn't hear anything... ;-)
10

maxage has been bound to this. Consider the following:

var dateFilter = function(value) {
  if(value < this) return value;
}
var dates = [1,2,3];
console.log(dates.filter(dateFilter,2));
> [1] // Output.

The MDN documentation shows the filter signature to be array.filter(callback[, thisObject])

Comments

3

Maybe there is no need to overcomplicate the things, try the simple way:

var maxage = 500,
    newDates = dates.filter(function(value) {
        return Date.now() - value < maxage;
    });

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.