Categories
JavaScript Answers

How to Sort an Object by Value in JavaScript?

Spread the love

Sometimes, we want to sort an object by value in JavaScript.

In this article, we’ll look at how to sort an object by value in JavaScript.

Sort an Object by Value in JavaScript

To sort an object by value in JavaScript, we can use the Object.values method to get the property values from the object in an array.

Then we can use the JavaScript sort method to sort the array values.

For instance, we can write:

const dict = {
  "x": 1,
  "y": 6,
  "z": 9,
  "a": 5,
  "b": 7,
  "c": 11,
  "d": 17,
  "t": 3
};

const items = Object.values(dict).sort((first, second) => {
  return second - first;
});

console.log(items)

We create the dict object with values we want to sort.

Then we call Object.values with dict to return an array of dict property values.

Next, we call sort with a callback that returns how we want to sort the items.

We subtract second by first to sort the property values in descending order.

Therefore, the console log logs:

[17, 11, 9, 7, 6, 5, 3, 1]

Conclusion

To sort an object by value in JavaScript, we can use the Object.values method to get the property values from the object in an array.

Then we can use the JavaScript sort method to sort the array values.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *