0
0
JavascriptHow-ToBeginner · 3 min read

How to Sort Object by Value in JavaScript Easily

To sort an object by its values in JavaScript, convert the object into an array of key-value pairs using Object.entries(), then use Array.sort() on the values. Finally, you can convert the sorted array back to an object if needed.
📐

Syntax

Use Object.entries(obj) to get an array of key-value pairs from the object. Then apply array.sort((a, b) => a[1] - b[1]) to sort by the values (which are at index 1). Optionally, use Object.fromEntries() to convert the sorted array back to an object.

  • obj: The original object.
  • Object.entries(obj): Converts object to array of [key, value].
  • array.sort(): Sorts the array by comparing values.
  • Object.fromEntries(): Converts array back to object.
javascript
const sortedArray = Object.entries(obj).sort((a, b) => a[1] - b[1]);
const sortedObj = Object.fromEntries(sortedArray);
💻

Example

This example shows how to sort an object by its values in ascending order and then convert it back to an object.

javascript
const scores = { alice: 50, bob: 75, charlie: 40 };

const sortedEntries = Object.entries(scores).sort((a, b) => a[1] - b[1]);
const sortedScores = Object.fromEntries(sortedEntries);

console.log(sortedScores);
Output
{"charlie":40,"alice":50,"bob":75}
⚠️

Common Pitfalls

One common mistake is trying to sort an object directly, which is not possible because objects are unordered collections. Another is forgetting that Array.sort() sorts in place and returns the sorted array, so you must capture the result or chain properly.

Also, sorting by values requires accessing the second element of each entry (a[1] and b[1]), not the keys.

javascript
const obj = { a: 3, b: 1, c: 2 };

// Wrong: trying to sort object directly (does nothing)
// obj.sort(); // Error: obj.sort is not a function

// Correct way:
const sorted = Object.entries(obj).sort((a, b) => a[1] - b[1]);
console.log(sorted);
Output
[["b",1],["c",2],["a",3]]
📊

Quick Reference

  • Convert object to array: Object.entries(obj)
  • Sort array by value: array.sort((a, b) => a[1] - b[1])
  • Convert back to object: Object.fromEntries(array)

Key Takeaways

You cannot sort an object directly; convert it to an array first.
Use Object.entries() to get key-value pairs as an array.
Sort the array by comparing the second element (value) of each pair.
Convert the sorted array back to an object with Object.fromEntries().
Remember Array.sort() changes the array in place and returns it.