Search code examples
javascriptjqueryunderscore.js

Get multiple maximum values from an array of values


For example in underscore/lowdash you can use _.max(list, [iterator], [context]) function to receive one maximum value. But I want to have it returned multiple maximum values if they are all equal.

var stooges = [{name: 'moe', age: 40}, {name: 'larry', age: 50}, {name: 'curly', age: 50}];

_.max(stooges, function(stooge){ return stooge.age; });

=> {name: 'curly', age: 50};

I want to have somthing like this:

var stooges = [{name: 'moe', age: 40}, {name: 'larry', age: 50}, {name: 'curly', age: 50}];

_.multiplemax(stooges, function(stooge){ return stooge.age; });

=> [{name: 'curly', age: 50},  {name: 'larry', age: 50 ];

Using underscore is ok.


Solution

  • Is there any special requirements like you cant not combine multiple functions to do multiplemax. If no, I have 2 solutions in my mind

    The simplest solution would be to use _.max to find the max age of the array, then use _.filter to filter all values that are equal to max age

    Another solution is to use _.groupBy to group the array by age and then get the group with max age

    Something like this

    function multiplemax(arr, compare) {
      var groups = _.groupBy(arr, compare);
      var keys = _.keys(groups);
      var max = _.max(keys);
      return groups[max];
    }
    

    more "underscore"

    _.mixin({
      multiplemax: function(arr, fn) {
        var groups = _.groupBy(arr, fn);
        var keys = _.keys(groups);
        var max = _.max(keys);
        return groups[max];
      }
    })
    

    Or using max + filter

    function multiplemax(arr, compare) {
      var max = _.max(arr, function(v){return v[compare]});
      return _.filter(arr, function(v){return v[compare]==max[compare]});
    }