sort object array by key

How to Sort Object Array by Date Keys

JavaScript objects are key-value pairs that allow you to store diverse and large amount of data in a compact and easy to retrieve manner. You can quickly access any JS object’s value using its key. Each value can, in turn, be another JS data structure such as string, integer, array, set, etc. Sometimes you may need to sort object array by date keys. In this article, we will learn how to do this.

How to Sort Object Array by Date Keys

Let us say you have the following JS object.

   var obj = {
  "2022-01-28 00:00:00.000": [],
  "2022-01-29 00:00:00.000": [],
  "2022-01-30 00:00:00.000": [],
  "2022-02-02 00:00:00.000": []

The order of keys in JS object cannot be changed and they don’t have a fixed order. So if you want to sort the object array by date keys you need to write function that extracts the keys, sort them and returns their values. Here is an example to do so.

var objKeys = Object.keys(obj);
objKeys.forEach( (value) => {
    // do something with obj[value]
    return obj[value];

Let us look at the above code in detail. First, we get all the keys in our object using keys() function. It returns an array of all keys in our object.

Then we sort these keys using sort() function.

Finally, we call forEach() function on the array of keys, to iterate through the sorted keys one by one. For each iteration, we simply return their value. You can modify this part according to your requirement.

As mentioned earlier, the order of keys in JS objects is automatically assigned, not intuitive and cannot be changed. You need to do the sorting while retrieving the key-value pairs.

You need to do this by extracting all the keys and sorting them, and then iterating through the sorted list of keys to retriever their corresponding values.

Also read:

How to Pad Numbers With Leading Zeros in JavaScript
How to Get Random Element from Array in JavaScript
How to Simulate KeyPress in JavaScript
How to Call Function Using Variable Name in JavaScript
How to Detect Tab/Browser Closing in JavaScript

Leave a Reply

Your email address will not be published.