# How to sort object property by values in JavaScript

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Jul 12, 2022. Topics: JavaScript.
Canonical URL: https://attacomsian.com/blog/javascript-sort-object

> A quick guide to learn about different ways to sort an object's properties by their values in JavaScript.

By default, JavaScript [objects](https://attacomsian.com/blog/objects-prototypes-classes-javascript#objects) are unordered. If you [iterate over the properties](https://attacomsian.com/blog/javascript-iterate-objects) 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](https://attacomsian.com/blog/javascript-convert-object-to-array), sort that array, and then convert that array back into an object.

Here is an example:

```javascript
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](https://attacomsian.com/blog/object-entries-values-javascript#objectentries-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](https://attacomsian.com/blog/javascript-object-array-destructuring#object-destructuring) from the array returned by  `Object.entries()`.

Finally, we call the [`reduce()` method](https://attacomsian.com/blog/javascript-array-reduce) 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:

```javascript
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:

```javascript
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](https://attacomsian.com/blog/javascript-sort-array-of-objects) to learn how to sort an array of objects by a property value in JavaScript.
