How To Sort An Array Of Objects In JavaScript

Spread the love

In this article, I am going to show you how to sort an array of objects in javascript.

I am writing this post because I have come across this issue. I have an array of objects. I wanted to sort this object in reverse order.

I have tried using the reverse() method of array but sorting doesn’t happen properly. I have searched across the blogs and I have come across one solution. I am going to share this here.

Let’s take a sample array like below

let object = [
      {
        title: "Display an array",
        date: "2020-03-11T14:49:13.541Z",
        order: 2
      },
      {
        title: "Reverse an array",
        date: "2020-04-13T14:49:13.541Z",
        order: 1
      },
      {
        title: "Sort an array",
        date: "2020-04-11T14:49:13.541Z",
        order: 3
      }
];

If you see the above array, it is sorted by the name by default.

So If we want to sort it by the date, we need to do it by the following way.

If we want to sort it by the latest date, the code will be

object.sort((a,b) => {
      return (new Date(b.date) - new Date(a.date))
});

If we want to sort it by the oldest date, the code will be

object.sort((a,b) => {
      return (new Date(a.date) - new Date(b.date))
});

Similarly, If we want to sort the object in ascending order, the code will be

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

and If we want to sort the object in descending order, the code will be

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

Now, Let’s say if we want to sort the above object using title property,

If we want to sort the object based on string, then we have to use localeCompare() method of string. So the code will be

object.sort((a,b) => {
      let str1 = a.title.toLowerCase(), 
          str2 = b.title.toLowerCase();
      return str1.localeCompare(str2);
});

If we want to sort the object in reverse alphabetical order, we need to reverse the str1 and str2 in return statement like below.

object.sort((a,b) => {
      let str1 = a.title.toLowerCase(), 
          str2 = b.title.toLowerCase();
      return str2.localeCompare(str1);
});

This is how we sort the array of objects in javascript. I hope this article will help you.

Happy Coding!

1 thought on “How To Sort An Array Of Objects In JavaScript”

Leave a Comment