javascript - get top N values' keys of an Object -


demo object:

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

wanted result: (get top 3 keys value)

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

explenation:

for given key/value basic object, how 3 top values, not values keys? keys anything. lets values integers.

performance should in mind.

you can extract properties array, sort 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 want result object, reduce one

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

Comments

Popular posts from this blog

c# - Binding a comma separated list to a List<int> in asp.net web api -

Delphi 7 and decode UTF-8 base64 -

html - Is there any way to exclude a single element from the style? (Bootstrap) -