3

I have the following function:

function isBigEnough(element, index, array) {
  return (element >= 10);
}
var filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
// filtered is [12, 130, 44] 

How can I return values that are larger than (or equal to) a number other than 10? For example, array.filter(isBigEnough(15)) would give me 44, 130

Jackie Chan
  • 2,654
  • 6
  • 35
  • 70
  • http://stackoverflow.com/q/2722159/1176601 – Aprillion Nov 19 '12 at 06:44
  • 1
    _"Also i would like to put loops in the function"_ - What do you mean by that? It doesn't make sense to put loops in your `isBigEnough()` function if you are using it as a callback for `filter()`. – nnnnnn Nov 19 '12 at 07:08
  • Sorry for my English, meant a totally different thing. After review, I removed this sentence – Jackie Chan Nov 19 '12 at 22:19

1 Answers1

15

Functions are first-class citizens in JS, so you can create a function which returns another function:

function isBigEnough(value) {
  return function(element, index, array) {
    return (element >= value);
  }
}
var filtered = [12, 5, 8, 130, 44].filter(isBigEnough(10));
carlosfigueira
  • 85,035
  • 14
  • 131
  • 171