Sort Object.entries To Rank Record Values
Object.entries turns a record into sortable pairs, and sorting plus slice plus fromEntries rebuilds it as a ranking without ever touching the original.
Code
const votes = { alpha: 3, beta: 7, gamma: 7, delta: 1 };
// entries turns the record into [key, value] pairs: sort by votes descending, ties broken by key name ascending
const ranking = Object.entries(votes).sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]));
console.log('pairs :', ranking.map((pair) => pair[0] + ':' + pair[1]).join(' | '));
// fromEntries rebuilds the record: string keys keep insertion order, so key order is rank order
const ranked = Object.fromEntries(ranking);
console.log('ranked:', Object.keys(ranked).join(','));
// slice takes the top three; the original record is never modified
const podium = Object.fromEntries(ranking.slice(0, 3));
console.log('podium:', Object.keys(podium).join(','));
console.log('winner:', ranking[0][0], 'with', ranking[0][1], 'votes');
console.log('original intact:', votes.beta === 7 && Object.keys(votes).join(',') === 'alpha,beta,gamma,delta');How it works
The file’s state is a handful of top-level bindings: votes, ranking, ranked, podium.
The top-level object literal pins alpha, beta, gamma, delta as plain values — no derivation, no imports behind them.
Putting it to use
Running the file prints labeled results such as pairs :, ranked:, podium: — each operation’s effect is visible in the output.
Core lines
const ranking = Object.entries(votes).sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]));
Interactive Tools for This Topic
Line SorterSort text lines ascending or descending with numeric-aware ordering, duplicate removal, empty-line filtering, and locale-aware comparison.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- Are there third-party dependencies?
- No. The dependency list is empty; the code stays inside the standard library. Its state lives in module-level bindings: `votes`, `ranking`, `ranked`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.