How to sort object property by values in JavaScript

By default, JavaScript objects are unordered. If you iterate over the properties of an object twice in succession, there is no guarantee that they'll come out in the same order the second time.

If you need an object's properties sorted by their values, convert them into an array, sort that array, and then convert that array back into an object.

Here is an example:

const prices = {
  butter: 3.5,
  pizza: 9.99,
  milk: 2.99
}

const sorted = Object.entries(prices)
  .sort(([, a], [, b]) => a - b)
  .reduce(
    (r, [k, v]) => ({
      ...r,
      [k]: v
    }),
    {}
  )

console.log(sorted)
// { milk: 2.99, butter: 3.5, pizza: 9.99 }

We use Object.entries() method to get an array of array of key-value pairs from the prices object.

Then we call the sort() method with a callback to sort the values that we just destructured from the array returned by Object.entries().

Finally, we call the reduce() method with a callback to merge the r object with the k and v key-value pair.

Object.keys() method

Another way to sort an object's properties by their values is to get the keys from the Object.keys() method and then do the sorting the same way:

const sorted = Object.keys(prices)
  .sort((key1, key2) => prices[key1] - prices[key2])
  .reduce(
    (obj, key) => ({
      ...obj,
      [key]: prices[key]
    }),
    {}
  )

console.log(sorted)
// { milk: 2.99, butter: 3.5, pizza: 9.99 }

Object.fromEntries() method

Instead of using reduce(), we can also use Object.fromEntries() to convert the sorted array back to an object as shown below:

const sorted = Object.fromEntries(
    Object.entries(prices).sort(([, a], [, b]) => a - b)
)

console.log(sorted)
// { milk: 2.99, butter: 3.5, pizza: 9.99 }

The Object.fromEntries() method was introduced in ES10 (ECMAScript 2019). It takes an array of array of key-value pairs as input and converts it into an object.

Take a look at this article to learn how to sort an array of objects by a property value in JavaScript.

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.