4

Demo Object:

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

Wanted result: (get top 3 keys by value)

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

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.

performance should be in mind.

vsync
  • 118,978
  • 58
  • 307
  • 400
  • 1
    Reading this now, I can't seem to understand my own question :) what was I thinking... – vsync Nov 03 '17 at 21:17

2 Answers2

11

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;
}, {});
Pointy
  • 405,095
  • 59
  • 585
  • 614
  • 1
    For completeness: `Object.keys` will only retrieve enumerable properties. `Object.getOwnPropertyNames` can be used to retrieve non-enumerable ones too. – Oriol Aug 30 '15 at 23:50
2

Get key/value pairs:

let pairs = Object.entries(foo);

Sort them:

pairs.sort((a, b) => a[1] - b[1]);

Turn some back into an object:

let result = Object.fromEntries(pairs.slice(-3));
Ry-
  • 218,210
  • 55
  • 464
  • 476