Sort object keys in JavaScript

In this tutorial, we will see how to sort Object keys in ascending or descending order in JavaScript.

Sort object keys in ascending or descending order in Javascript

To sort the object keys, we will first get all the objects keys in an array using Object.keys() and then sort the array using Array.sort() method.

Get all the keys of the Object in an array

Object.keys() is an inbuilt method in JavaScript to get the object keys in an array.

const obj = {
  2: 'a',
  4: 'b',
  1: 'c',
  3: 'd'
};

console.log(Object.keys(obj));
// ["1","2","3","4"]

If you notice, even if we have used the numeric keys, the array has returned them in sorted order, that is because unlike Map, JavaScript objects convert’s the keys to string and insert them in sorted order.

const obj = {
  2: 'a',
  4: 'b',
  1: 'c',
  3: 'd'
};

console.log(obj);

/*{
  "1": "c",
  "2": "a",
  "3": "d",
  "4": "b"
}*/

Even the keys are inserted after the object is initialized.

const obj = {
  2: 'a',
  4: 'b',
  1: 'c',
  5: 'd'
};

obj[3] = 'f';

console.log(obj);

/*{
  "1": "c",
  "2": "a",
  "3": "f",
  "4": "b",
  "5": "d"
}*/

Thus it is recommended to use JavaScript map to store the unique key-value pairs and also JavaScript maps can be sorted in ascending or descending order.

This object behavior is only for the numeric keys, for the string keys, it maintains the order.

const obj = {
  'e': 1,
  'c': 2,
  'b': 3,
  'd': 4,
  'a': 5
};

console.log(obj);
/*
{
  "e": 1,
  "c": 2,
  "b": 3,
  "d": 4,
  "a": 5
}
*/

console.log(Object.keys(obj));
//["e","c","b","d","a"]

Sort the object keys in JavaScript

Now that we have the object keys in an array, we can use the Array.sort() method for sorting.

Sorting the object keys in Ascending order in JavaScript

The Array.sort() method accepts a callback function as input and based on the return value of it, the sorting order will be decided.

const obj = {
  'e': 1,
  'c': 2,
  'b': 3,
  'd': 4,
  'a': 5
};

const objKeys = Object.keys(obj);

const sortedKeys = objKeys.sort((a, b) => a > b);

console.log(sortedKeys);
// ["a","b","c","d","e"]

Here we have used the simplest way to sort the string, You can check out the detailed article on how to sort an array of strings in ascending or descending order with and without being case-sensitive.

Sorting the object keys in Descending order in JavaScript

To sort in descending order, compare the next string with the first string.

const obj = {
  'e': 1,
  'c': 2,
  'b': 3,
  'd': 4,
  'a': 5
};

const objKeys = Object.keys(obj);

const sortedKeys = objKeys.sort((a, b) => b > a);

console.log(sortedKeys);
//["e","d","c","b","a"]

For numeric keys, you will need to update the comparison logic of the Array.sort().