How to sort object property by values in JavaScript

published: 24 Sep 2022

2 min read

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.

How to sort object property by values in JavaScript | Coding Tips And Tricks

Are we missing something?  Help us improve this article. Reach out to us.

Are you looking for other code tips?

Check out what's on in the category: javascript, programming
Check out what's on in the tag: javascript, programming, array