How To Sort An Object By Key/Value In JavaScript

Jennifer Yoo
JavaScript in Plain English
3 min readJan 19, 2021

--

Objects consist of key and value pairs. A key can be a string or symbol and a value can be any type.

There might be instances where you want to sort your object by key or value. However, there are no in-built JavaScript methods to sort object properties.

Here we have an object, pets. The key is a string which represents the type of pet. The value is an integer which represents the number of the specified pet.

There are 3 object methods that can be used to parse through the data.

Object.entries()

This method returns an array of a given object’s enumerable property pairs.

Since the object was converted to an array, the data can be more easily manipulated to find specific information. In the case we want to find out the which pet had the highest number, a sort method can be used.

This will order the array in descending order. b[1] - a[1] will sort the array by comparing the values.

Now we have a sorted array of arrays and we can easily extract the pair with the highest key value.

Object.keys()

This method will return an array of a given object’s enumerable property keys.

Object.values()

This method will return an array of a given object’s enumerable property values.

This method is useful in events where you only care for the value. For example, finding the highest or lowest values or most frequent.

These three object methods all convert the given object into an array giving us more flexibility in terms to using in-built Javascript methods to manipulate the data.

--

--