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
Post a Comment