Sorting objects in JavaScript e.c. how to get sorted values from an object.

Gulnoza Muminova
4 min readJan 24, 2020

An object type is a collection of key-value pairs — properties in JavaScrip. KEY can be a string or a symbol, and VALUE can be any type (str, int, obj, arr), or even functions. There is no order for the object properties.

obj = {
'someKey': someValue,
'anotherKey': anotherValue
}

What if you have an object and you need to sort properties by keys or values?

For example, you have this problem,

You have a grossaryList object, where the ‘key’ is the name of food and ‘value’ is the count. You need to return two keys with the greatest value from an object.

Example:

Input: grossaryList = {
'bread': 1,
'apple': 6,
'milk': 1,
'orange': 3,
'broccoli': 2
}
//apple and orange are with the most count (6 and 3)
Output: ['apple', 'orange']

How can I accomplish this, if I cannot sort object properties, since there is no order there, remember?

There are 3 useful methods to get ‘keys’ or ‘values’ or ‘key: value’ data from an object. I will use Object.entries, because I need both key: value for my task.

  • Object.keys(grossaryList) => [‘bread’, ‘apple’, ‘milk’, ’orange’, ’broccoli’]
  • Object.values(grossaryList) => [‘1’, ‘6’, ‘1’, ’3’, ’2’]
  • Object.entries(grossaryList) => [['bread', 1],['apple', 6],['milk', 1],['orange', 3],['broccoli', 2]]

According to MDN Documentation: “The Object.entries() method returns an array of a given object's own enumerable string-keyed property [key, value] pairs, in the same order as that provided by a for...in loop. (The only important difference is that a for...in loop enumerates properties in the prototype chain as well).”

grossaryList = {
'bread': 1,
'apple': 6,
'milk': 1,
'orange': 3,
'broccoli': 2
}
return Object.entries(grossaryList) //=>
[['bread',1],['apple', 6],['milk', 1],['orange', 3],['broccoli', 2]]
Testing Object.entries() method

The order of the array returned by Object.entries() does not depend on how an object is defined.

For certain ordering, you need to sort the array first. We can use the sort() method which in our case should look as follows:

grossaryList = {
'bread': 1,
'apple': 6,
'milk': 1,
'orange': 3,
'broccoli': 2
}
return Object.entries(grossaryList).sort((a,b) => b[1]-a[1])//=>
[['apple', 6],['orange', 3],['broccoli', 2],['bread',1],['milk', 1]]
Testing sort() method on Object.entries() method.

As you can see we got an array of arrays sorted by values as the result.

Object.entries(grossaryList).sort((a,b) => b[1]-a[1]),where a meens current element and b meens next element in array.
Because we have array of arrays [[key, value]] we need another brackets b[1] to compare by second element in inner array which meens compare by values.

As we are interested just in the keys from a sorted array, as the next step I am going to use array’s method map() to achieve that.


function sortObjectEntries(obj){
return Object.entries(obj).sort((a,b)=>b[1]-a[1]).map(el=>el[0])
}
Testing map() method on Object.entries().sort() methods

Great! We got an array with all keys sorted by values :)).

What if we are interested only in a certain number, N, of keys? This part can be easily achieved by using array’s method slice().

grossaryList = {
'bread': 1,
'apple': 6,
'milk': 1,
'orange': 3,
'broccoli': 2
}
function sortObjectEntries(obj, n){
return Object.entries(obj).sort((a,b)=>b[1]-a[1]).map(el=>el[0]).slice(0,n)
}
Testing slice() method on Object.entries().sort().map() methods

What if you have the keys with the same values in your list, for example:

grossaryList = {
'cherry': 6,
'milk': 3,
'broccoli': 4,
'orange': 3,
'apple': 6,
'bread': 4
}

Here ‘cherry’ and ‘apple’ have the same value 6, ‘broccoli’ and ‘bread’ have the same value 4, so probably we need sort by ‘key’ alphabetically if values are the same.

I tried not to use sort() method twice for sorting by keys and sorting by values. After looking for a different approach, I came up with a solution :).

Inside sort function, first we check if value a and value b are the same. If yes, we check their key a and key b, are they in alphabetical order. If no swap key a and key b, else don’t do anything.

function sortObjectEntries(obj, n){

let sortedList = []
//Sorting by values asc
sortedList = Object.entries(obj).sort((a,b)=>{
if(b[1] > a[1]) return 1;
else if(b[1] < a[1]) return -1;

//if values are same do edition checking if keys are in the right order
else {
if(a[0] > b[0]) return 1;
else if(a[0] < b[0]) return -1;
else return 0
}

})
// return first n values from sortedList
return sortedList.map(el=>el[0]).slice(0,n)
}

That’s it! We got the right output, even though we had the same values for different keys, but this logic was able to handle it.

I’ve broken down the solution for a better understanding of each step.

Thank you for your patience and for making it to the end!

--

--