Sorting JavaScript Object Properties by Values

Oct 22, 2025 · Programming · 21 views · 7.8

Keywords: JavaScript | Sorting | Object Properties | Array Methods | ES6

Abstract: This article explores methods to sort JavaScript object properties based on their values, covering traditional approaches with loops and arrays, modern techniques using Object.entries() and sort(), and ES10 features like Object.fromEntries(). It includes rewritten code examples, in-depth explanations, and best practices for developers.

Introduction

In JavaScript, objects are collections of key-value pairs, but property order is not guaranteed by the ECMAScript specification. However, for data display or processing, developers often need to sort object properties by value. Based on Q&A data and reference articles, this article analyzes various sorting methods with rewritten code and deep insights.

Traditional Method: Using Loops and Arrays

In early JavaScript, objects can be converted to arrays via loops, sorted, and then reconstructed. This method has broad compatibility but relies on array order properties.

const list = {
  "you": 100,
  "me": 75,
  "foo": 116,
  "bar": 15
};

let sortable = [];
for (let key in list) {
  if (list.hasOwnProperty(key)) {
    sortable.push([key, list[key]]);
  }
}

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

const sortedObj = {};
sortable.forEach(item => {
  sortedObj[item[0]] = item[1];
});

console.log(sortedObj); // Output: { bar: 15, me: 75, you: 100, foo: 116 }

This code uses a for...in loop to iterate over object properties, stores each key-value pair in an array, sorts by value with a comparison function, and rebuilds the object using forEach. Note that hasOwnProperty checks avoid prototype chain properties.

Modern Method with Object.entries() and sort()

ES8 introduced Object.entries(), simplifying object-to-array conversion. Combined with array methods, the code becomes more concise.

const list = {
  "you": 100,
  "me": 75,
  "foo": 116,
  "bar": 15
};

const sortedArray = Object.entries(list)
  .sort(([, a], [, b]) => a - b);

const sortedObj = sortedArray.reduce((acc, [key, value]) => {
  acc[key] = value;
  return acc;
}, {});

console.log(sortedObj); // Output: { bar: 15, me: 75, you: 100, foo: 116 }

Object.entries() returns an array of key-value pairs, sort() uses destructuring to access values, and reduce() accumulates into a new object. This approach leverages functional programming for better readability.

ES10 Method with Object.fromEntries()

ES10's Object.fromEntries() directly converts a sorted array back to an object, making the code more compact.

const list = {
  "you": 100,
  "me": 75,
  "foo": 116,
  "bar": 15
};

const sortedObj = Object.fromEntries(
  Object.entries(list).sort(([, a], [, b]) => a - b)
);

console.log(sortedObj); // Output: { bar: 15, me: 75, you: 100, foo: 116 }

This method chains Object.entries(), sort(), and Object.fromEntries(), reducing intermediate variables and suitable for modern JavaScript environments.

Alternative Approach with Object.keys()

Sorting key arrays indirectly achieves ordering, useful for iteration scenarios.

const list = {
  "you": 100,
  "me": 75,
  "foo": 116,
  "bar": 15
};

const sortedKeys = Object.keys(list).sort((a, b) => list[a] - list[b]);

const sortedObj = {};
sortedKeys.forEach(key => {
  sortedObj[key] = list[key];
});

console.log(sortedObj); // Output: { bar: 15, me: 75, you: 100, foo: 116 }

Object.keys() extracts key arrays, sorts based on corresponding values, and reconstructs the object. This does not directly alter the object but provides a sorted view.

Considerations and Best Practices

JavaScript object property order is unreliable; modern engines may maintain insertion order, but it is not standardized. Reference article 1 emphasizes that objects are designed for key-based lookup, not ordering; arrays are recommended for ordered data. The Array.prototype.sort() method (reference article 2) is central, requiring a comparison function that is pure, stable, reflexive, antisymmetric, and transitive. For example, use subtraction for numbers and localeCompare() for strings. Avoid relying on object order for critical logic; prefer arrays for ordered collections.

Conclusion

Various methods exist to sort JavaScript object properties by value, from traditional loops to modern ES6+ features. Object.entries() and Object.fromEntries() offer efficient solutions. Developers should understand object limitations and choose data structures appropriately. Through the examples and analysis in this article, code quality and maintainability can be enhanced.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.