Sort the Keys of an Object with JavaScript

Hero image for Sort the Keys of an Object with JavaScript. Image by Samantha Lam.
Hero image for 'Sort the Keys of an Object with JavaScript.' Image by Samantha Lam.

As you probably know, an object in JavaScript is an unordered collection of keyvalue pairs. However, in certain situations, you may find that you need to sort the keys of an object alphabetically or numerically.

This can be achieved fairly easily by:

  1. Getting an array of the object's keys;
  2. Sorting them;
  3. Using reduce() to rebuild the object, in the order of the keys.

For example:

const sortObject = obj => {  // get the keys of the object  var keys = Object.keys(obj);  // sort the keys  keys.sort();  // use reduce to rebuild the object  return keys.reduce((sortedObj, key) => {    sortedObj[key] = obj[key];    return sortedObj;  }, {});};

You could use this function like this:

let myObj = { c: 1, a: 2, b: 3 };console.log(sortObject(myObj));//=> {a: 2, b: 3, c: 1}

Do bear in mind that this method will create a new object, rather than modifying the original one.

Also, If you want to sort the object numerically, you would need to pass a function as a parameter to the sort method like this:

keys.sort((a, b) => {  return a - b;});

Easy!


Categories:

  1. Front‑End Development
  2. JavaScript