Sorting an Array of Objects in JavaScript

Sorting an Array of Objects in JavaScript

So, let’s say you have a large Array of Objects, looking like this (snippet)

[
  {
    "timestamp": 1584258,
    "loaded": true
  },
  {
    "timestamp": 8751845,
    "loaded": false
  },
  {
    "timestamp": 9875841,
    "loaded": false
  }
]

Now you want to sort these Objects in ascending or descending order, based on the key: timestamp
That’s very easy, and you can do it one of two ways

First way: Write a sorting function and call it as the parameter in the Array.sort() method

//Assuming your array is defined as db

//This is for sorting in Descending order
const sortDesc = (a,b) => {
  return b.timestamp - a.timestamp;
}

//This is for sorting in Ascending order
const sortAsc = (a,b) => {
  return a.timestamp - b.timestamp;
}


db.sort(sortDesc);

The other way, is to one-line it all into the Array.sort() call

//Again assuming the array is db

//Sorting in Descending order
db.sort((a,b) => b.timestamp - a.timestamp);

//Sorting in Ascending order
db.sort((a,b) => a.timestamp - b.timestamp);

I prefer to write the functions out, like the first example, but that’s just personal preference.

Leave a Reply

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