Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass variable value to .filter()

Tags:

javascript

The following code is taken from the reference here:

function isBigEnough(value) {
      return value >= 10;
    }

    var filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
    // filtered is [12, 130, 44]

I want to know if I can dynamically change the value of 10 in the return line by passing in a variable. From the reference I cannot figure out how to do this. I want to call the same filter callback but pass in a unique value for a regex test.

So it would look something like:

function isBigEnough(value, num) {
      return value >= num;
    }
like image 852
Michael Rader Avatar asked Dec 11 '22 13:12

Michael Rader


2 Answers

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

If you really wanted to keep a named function to call back to, you could partially apply a parameter with bind:

function isBigEnough(minSize, value) {
  return value >= minSize;
}

var filtered = [12, 5, 8, 130, 44].filter(isBigEnough.bind(null,10));

Here, bind will return a new function with the leftmost parameter bound to 10 (the first argument, the one that is null, is what gets passed as this to the function when being invoked). So the parameter that filter passes in will show up as the second value in the callback.

like image 72
PMV Avatar answered Dec 24 '22 13:12

PMV


Try this

function isBigEnough(num) {
  return function(value) {
    return value >= num;
  }
}

And then

[12, 5, 8, 130, 44].filter(isBigEnough(10));

How does this work?

  • calling isBigEnough(10) returns an anonymous function
  • then that anonymous function is passed to filter
like image 34
akuhn Avatar answered Dec 24 '22 13:12

akuhn