admin管理员组文章数量:1279124
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.
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.
Share Improve this question edited Jan 11, 2020 at 21:13 vsync asked Aug 30, 2015 at 23:38 vsyncvsync 131k59 gold badges340 silver badges422 bronze badges 1- 1 Reading this now, I can't seem to understand my own question :) what was I thinking... – vsync Commented Nov 3, 2017 at 21:17
2 Answers
Reset to default 11You 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;
}, {});
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));
本文标签: javascriptObject filter by N highest numeric values (of keys)Stack Overflow
版权声明:本文标题:javascript - Object filter by N highest numeric values (of keys) - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741271433a2369378.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论