Skip to content
Advertisement

min_by,max_by equivalent functions in javascript

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:

Array.prototype.minBy = function(lambda) {
    var lambdaFn;
    if (typeof(lambda) === "function") {
        lambdaFn = lambda;
    } else {
        lambdaFn = function(x){
            return x[lambda];
        }
    }
    var mapped = this.map(lambdaFn); 
    var minValue = Math.min.apply(Math, mapped); 
    return this[mapped.indexOf(minValue)];
}

So the ruby example becomes:

['albatross', 'dog', 'horse'].minBy(function(x){return x.length })  // = 'dog'

or:

['albatross', 'dog', 'horse'].minBy("length") // = 'dog'
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement