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
?
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 );
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.
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 .
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
}
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])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With