Is there any javascript library that contains functions like min_by,max_by in Ruby, which allow you pass a lambda as a criteria to compare. I found not such things in JQuery and underscore.js .
Advertisement
Answer
To use this in the same way as Ruby, ie call it on the array:
JavaScript
x
14
14
1
Array.prototype.minBy = function(lambda) {
2
var lambdaFn;
3
if (typeof(lambda) === "function") {
4
lambdaFn = lambda;
5
} else {
6
lambdaFn = function(x){
7
return x[lambda];
8
}
9
}
10
var mapped = this.map(lambdaFn);
11
var minValue = Math.min.apply(Math, mapped);
12
return this[mapped.indexOf(minValue)];
13
}
14
So the ruby example becomes:
JavaScript
1
2
1
['albatross', 'dog', 'horse'].minBy(function(x){return x.length }) // = 'dog'
2
or:
JavaScript
1
2
1
['albatross', 'dog', 'horse'].minBy("length") // = 'dog'
2