Sort the Keys of an Object in JavaScript

avatar

Borislav Hadzhiev

Tue Feb 22 20222 min read

banner

Photo by Ant Rozetsky

Sort the Keys of an Object in JavaScript #

To sort the keys of an object:

  1. Use the Object.keys() method to get an array of the object's keys.
  2. Call the sort() method on the array.
  3. Call the reduce() method to get an object with sorted keys.
index.js
const obj = {z: 'three', a: 'one', b: 'two'}; const sorted = Object.keys(obj) .sort() .reduce((accumulator, key) => { accumulator[key] = obj[key]; return accumulator; }, {}); console.log(sorted); // 👉️ {a: 'one', b: 'two', z: 'three'}

We used the Object.keys method to get an array of the object's keys.

index.js
const obj = {z: 'three', a: 'one', b: 'two'}; // 👇️ ['z', 'a', 'b'] console.log(Object.keys(obj));

The next step is to use the Array.sort() method to sort the array of keys.

index.js
const obj = {z: 'three', a: 'one', b: 'two'}; // 👇️ ['a', 'b', 'z'] console.log(Object.keys(obj).sort());

At this point we have a sorted array containing the object's keys.

The last thing we have to do is use the Array.reduce method to iterate over the sorted array of keys and assign each key-value pair to an object.

index.js
const obj = {z: 'three', a: 'one', b: 'two'}; // 👇️ ['a', 'b', 'z'] console.log(Object.keys(obj).sort()); const sorted = Object.keys(obj) .sort() .reduce((accumulator, key) => { accumulator[key] = obj[key]; return accumulator; }, {}); console.log(sorted); // 👉️ {a: 'one', b: 'two', z: 'three'}

The function we passed to the reduce() method gets called with each element (key) in the array.

We've provided an empty object as the initial value for the accumulator variable.

On each iteration, we assign the key-value pair to the accumulator object and return the result.

The accumulator we return from the first iteration, gets passed as the accumulator for the second iteration and so on.

After the last iteration, the object contains all of the key-value pairs in a sorted order.

Make sure you pass an empty object as the second parameter to the reduce method - this is the initial value for the accumulator variable.

Note that this approach does not change the order of the keys in the original object, it creates a new object with sorted keys.

Now you can iterate over the sorted object by using the Object.keys() and the forEach() method.

index.js
const obj = {z: 'three', a: 'one', b: 'two'}; // 👇️ ['a', 'b', 'z'] console.log(Object.keys(obj).sort()); const sorted = Object.keys(obj) .sort() .reduce((accumulator, key) => { accumulator[key] = obj[key]; return accumulator; }, {}); Object.keys(sorted).forEach(key => { console.log(key, sorted[key]); // 👉️ a one, b two, z three });

The function we passed to the forEach() method gets called with each element (key) in the array.

Use the search field on my Home Page to filter through my more than 1,000 articles.