获取对象键的最高数值N值

问题描述:

var foo = {a:1, b:2, c:3, d:4, e:5, f:6, g:7}



通缉结果:(获得前3个键价值)



Wanted result: (get top 3 keys by value)

{e:5, f:6, g:7}






说明:



对于给定的密钥/ value基本对象,你如何获得3个顶部值,但不仅仅是值而是键?钥匙可以是任何东西。假设值是整数。


Explanation:

For a given key/value basic object, how would you get the 3 top values, but not just the values but also the keys? keys could be anything. lets say values are integers.

应该记住性能。

您可以将属性提取到数组中,然后对数组进行排序:

You can extract the properties into an array, then sort the array:

var foo = {a:1, b:2, c:3, d:4, e:5, f:6, g:7}
var props = Object.keys(foo).map(function(key) {
  return { key: key, value: this[key] };
}, foo);
props.sort(function(p1, p2) { return p2.value - p1.value; });
var topThree = props.slice(0, 3);

如果您希望将结果作为对象,只需将其缩减为一个

If you want the result as an object, just reduce it back to one

var topThreeObj = props.slice(0, 3).reduce(function(obj, prop) {
  obj[prop.key] = prop.value;
  return obj;
}, {});