获取对象键的最高数值N值 [英] Get highest numeric N values of Object keys

查看:69
本文介绍了获取对象键的最高数值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;
}, {});

这篇关于获取对象键的最高数值N值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆