温馨提示:本文翻译自stackoverflow.com,查看原文请点击:javascript - Top highest values in an object (more if there are more max values and they are the same)
javascript max

javascript - 对象中的最高最高值(如果存在更多最大值且相同,则更多)

发布于 2020-04-23 18:04:01

假设我有这样的对象:

var obj = {a : 5, b : 10, c : 15, d : 20, e : 20, f : 25};

我想获得前3个最高值-请注意,de键具有相同的值,我也需要获取键,因此它看起来像:

最大值:
f-25
d-20
e-20

例如,如果还有六个值并且四个相同:

var obj2 = {a:1, b:1, c:1, d:1, e:0,8, f: 0,5};

我需要显示4高。

最大值:
a-1
b-1
c-1
d-1

我猜有必要遍历所有对象属性以获取Math.max,但我还需要一些东西来用其键计数3个最大数字,如果还有更多的max(全部相同),我需要“全部获取” !”。

编辑:atm有很好的答案,所以我想我不会完成这段代码,只使用给定的示例:)

查看更多

提问者
Proo1931
被浏览
13
fubar 2020-02-13 04:46

这是一个示例实现,带有注释以解释每个步骤中发生的事情。

function maxValues(o, n) {
  // Get object values and sort descending
  const values = Object.values(o).sort((a, b) => b - a);
  
  // Check if more values exist than number required
  if (values.length <= n) return o;
  
  // Find nth maximum value
  const maxN = values[n - 1];
  
  // Filter object to return only key/value pairs where value >= maxN
  return Object.entries(o)
    .reduce((o, [k, v]) => v >= maxN ? { ...o, [k]: v } : o, {});
}

const a = maxValues({
  a: 5, 
  b: 10, 
  c: 15, 
  d: 20, 
  e: 20, 
  f: 25
}, 3);
console.log(a);

const b = maxValues({
  a: 1, 
  b: 1, 
  c: 1, 
  d: 1, 
  e: 0.8, 
  f: 0.5
}, 3);
console.log(b);

const c = maxValues({
  a: 5, 
  b: 10,
}, 3);
console.log(c);

传递给该Array.prototype.reduce函数的回调可以扩展为以下内容:

return Object.entries(o)
    .reduce(function (obj, [key, value]) {
        if (v >= maxN) {
            return Object.assign(obj, {
                [key]: value
            });
        } else {
            return obj;
        }
    }, {});

取而代之的是,我使用箭头函数表达式三元运算符传播语法将其压缩

三元运算符实质上是if/else语句的简写例如

condition ? true : false;
// or
v >= maxN ? { ...o, [k]: v } : o;

扩展语法允许将可迭代的值扩展到位。在这种情况下,它用于将现有key/value对从一个对象文字复制到另一对象文字。

const a = { first_name: 'Rob', gender: 'male' };
const b = { ...a, username: 'fubar' };

console.log(b); // { first_name: 'Rob', gender: 'male', username: 'fubar' };