Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass values to javascript array filter?

Tags:

javascript

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?

like image 463
lisovaccaro Avatar asked Dec 07 '12 01:12

lisovaccaro


People also ask

How do you pass parameters to a filter?

The easiest way would be simply to use an anonymous function and close over the variable you want to use: var minSize = 10; var filtered = [12, 5, 8, 130, 44]. filter( val => val >= minSize );

Can you use filter on an array of objects JavaScript?

One can use filter() function in JavaScript to filter the object array based on attributes. The filter() function will return a new array containing all the array elements that pass the given condition. If no elements pass the condition it returns an empty array.

What does the array filter () callback return?

filter() calls a provided callback function once for each element in an array, and constructs a new array of all the values for which callback returns a value that coerces to true .


2 Answers

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
}
like image 155
jAndy Avatar answered Oct 07 '22 03:10

jAndy


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])

like image 25
Aesthete Avatar answered Oct 07 '22 04:10

Aesthete