从值数组中获取多个最大值

问题描述 投票:0回答:5

例如,在

underscore/lowdash
中,您可以使用
_.max(list, [iterator], [context])
函数来接收一个最大值。但我想让它返回多个最大值(如果它们都相等)。

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

我想要这样的东西:

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

使用下划线即可。

javascript jquery underscore.js
5个回答
5
投票

是否有任何特殊要求,例如不能组合多个函数来执行 multiplemax。如果没有,我脑子里有 2 个解决方案

最简单的解决方案是使用 _.max 找到数组的最大值

age
,然后使用 _.filter 过滤所有等于 max
age

的值

另一种解决方案是使用 _.groupBy 按

age
对数组进行分组,然后获取具有 max
age

的组

类似这样的事情

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

更多“下划线”

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

或使用

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

1
投票

这样的事情应该可以解决问题。

_.mixin({
    multiplymax: function(items, comparitor) {
        comparitor = comparitor || _.identity;
        var max = comparitor(items.pop());
        var found = [max];
        _.each(items, function(item) {
            var val = comparitor(item);
            if(val > max) {
                found = [item];//empty
                max = val;
            } else if (val === max) {
                found.push(item);
            }
        });

        return found;
    }
})

更新修复了损坏的代码;)

_.multiplymax([{age: 1}, {age:5}, {age:7}, {age:7}, {age:3}], _.property("age")); // [{age:7}, {age:7}]

1
投票

这应该可以解决问题:

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

_.mixin( { multiplemax: function(list, field){

    var max = _.max(list, function(item){
        return item[field];
    });

    return _.filter(list, function(item){
        return item[field] === max[field];
    });
}});    

var oldStooges = _.multiplemax(stooges, 'age');

1
投票

这是使用 TypeScript 和 ES6 的现代版本:

const multipleMaxBy = <T>(list: T[], iteratee: (element: T) => number) => {
  const maxScore = Math.max(...list.map(iteratee));
  return list.filter((element) => iteratee(element) === maxScore);
};

0
投票

从最高到最低排序,并取

amount
值:

export const multipleMax = (list: any[], amount: number = 1) => {
  return _.take(_.reverse(_.orderBy(list)), amount)
}
© www.soinside.com 2019 - 2024. All rights reserved.