How To Sort Objects In Javascript – Simple Examples

Welcome to a tutorial and examples on how to sort objects in Javascript. Having trouble with sorting objects in Javascript? Sadly, there are no native functions nor direct ways to sort an object in Javascript.

To sort an object by the keys in Javascript, we need to extract the keys into an array first, sort it, then map it back.

  • var obj = { bow:"Bar", arrow:"Foo" };
  • var keys = Object.keys(obj);
  • keys.sort();
  • var sorted = {};
  • for (let k of keys) { sorted[k] = odata[k]; }

That covers the basics for sorting by the key, but read on for more examples for sorting the values plus nested objects!

ⓘ I have included a zip file with all the source code at the start of this tutorial, so you don’t have to copy-paste everything… Or if you just want to dive straight in.

 

 

REAL QUICK SLIDES

 

TABLE OF CONTENTS

Download & Notes Sort Object Useful Bits & Links
The End

 

DOWNLOAD & NOTES

Firstly, here is the download link to the example code as promised.

 

EXAMPLE CODE DOWNLOAD

Click here to download all the example source code, I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

QUICK NOTES

If you spot a bug, please feel free to comment below. I try to answer questions too, but it is one person versus the entire world… If you need answers urgently, please check out my list of websites to get help with programming.

 

 

SORT OBJECTS

All right, let us now get into the examples of how to sort an object in Javascript.

 

1) SORT OBJECTS BY THE KEY

1-sort-key.html
// (A) SORT FUNCTION
function oksort (obj) {
  // (A1) EXTRACT KEYS INTO ARRAY
  var keys = Object.keys(obj);

  // (A2) SORT THE ARRAY IN ASCENDING ORDER
  keys.sort();
  // TO SORT IN DESCENDING ORDER
  // keys.sort().reverse();

  // (A3) REARRANGE THE OBJECT
  let sorted = {};
  for (let k of keys) { sorted[k] = obj[k]; }
  return sorted;
}

// (B) GO!
var odata = oksort({
  grape : "Foo",
  banana : "Goo",
  lemon : "Hoo",
  apple : "Ioo",
});
console.log(odata);

As in the introduction, to sort an object:

  1. We have to extract the keys into an array. I.E. keys = ["grape", "banana", "lemon", "apple"]
  2. Sort the array of keys. I.E. keys = ["apple", "banana", "grape", "lemon"]
  3. Then “map” the keys back to their original values. I.E. for (let k of keys) { SORTED[k] = OBJECT[k]; }

This example is just “packaged” into a function for your convenience.

 

 

2) SORT OBJECTS BY THE VALUE

2-sort-value.html
// (A) SORT FUNCTION
function ovsort (obj) {
  // (A1) EXTRACT ENTRIES (KEY-VALUE)
  var entries = Object.entries(obj);

  // (A2) SORT
  entries.sort(function(a, b){
    return a[1].localeCompare(b[1]);
  });

  // (A3) REARRANGE BACK TO OBJECT
  var sorted = {};
  for (let i of entries) { sorted[i[0]] = i[1]; }
  return sorted;
}

// (B) GO!
var odata = ovsort({
  lemon : "Hoo",
  banana : "Foo",
  apple : "Ioo",
  grape : "Foo",
});
console.log(odata);

How do we sort an object by the values? Some may be thinking “just recycle the previous example, but extract the values instead”. That is the gist of it, but it suffers from a potential problem – If the object has duplicate values, we will have trouble “mapping” the values back to the original keys. So here’s a small roundabout:

  1. Extract the entries into an array. I.E. entries = [["lemon", "Hoo"], ["banana", "Foo"], ["apple", "Ioo"], ["grape", "Foo"]]
  2. Sort the entries by comparing the values. I.E. entries = [["banana", "Foo"], ["grape", "Foo"], ["lemon", "Hoo"], ["apple", "Ioo"]]
  3. “Reconstruct” the sorted array back into an object. I.E. for (let i of entries) { SORTED[i[0]] = i[1]; }

 

 

3) SORT NESTED OBJECTS

3-sort-nested.html
// (A) SORT FUNCTION
function onsort (obj) {
  // (A1) EXTRACT KEYS INTO ARRAY
  var keys = Object.keys(obj);

  // (A2) SORT THE ARRAY IN ASCENDING ORDER
  keys.sort();
  // TO SORT IN DESCENDING ORDER
  // keys.sort().reverse();

  // (A3) REARRANGE THE OBJECT
  let sorted = {};
  for (let k of keys) { 
    // RECURSIVE SORT NESTED OBJECTS
    let val = null;
    if (typeof obj[k] === 'object' && obj[k] !== null) {
      val = onsort(obj[k]);
    } else {
      val = obj[k];
    }
    sorted[k] = val;
  }

  // (A4) DONE
  return sorted;
}

// (B) GO!
var odata = onsort({
  grape : "Foo",
  banana : {
    red : "Aoo",
    green : "Boo",
    blue : "Coo"
  },
  lemon : "Hoo",
  apple : "Ioo",
});
console.log(odata);

Nested objects are nasty, but not quite. To sort a nested object, we simply modify the previous example a little to do some recursive magic – If a value is an object, we simply pass it into the sort function again.

 

 

USEFUL BITS & LINKS

That’s all for the main tutorial, and here is a small section on some extras and links that may be useful to you.

 

LIMITATIONS

Captain Obvious to the rescue. The above examples will only work with objects that are in the format of key-value; If the object has functions, array, or boolean values, it will not work.

P.S. We can compare numbers with ARRAY.sort(function(a, b){ return a - b; });

 

INFOGRAPHIC CHEAT SHEET

How To Sort Objects In Javascript (click to enlarge)

 

LINKS & REFERENCES

 

THE END

Thank you for reading, and we have come to the end. I hope that it has helped you to better understand, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

Leave a Comment

Your email address will not be published. Required fields are marked *