javascript sort by date – How to sort an array by date value in JavaScript?

javascript sort by date, Sorting an array of objects by number, string, date in JavaScript Example. javascript sort date ascending and descending, sort array by timestamp, sort array of objects by date.

javascript sort by date

You want to sort those website_list by the date property. You can use the sort() method of Array. Date Object: The Date object in JavaScript is used to represent a moment of time.

const website_list = [
  { title: 'Pakainfo', date: new Date('2022-06-28') },
  { title: 'Infinityknow', date: new Date('2022-06-10') },
  { title: 'W3diy', date: new Date('2022-06-22') }
]

Simplest Way

array.sort(function(a,b){
  return new Date(b.date) - new Date(a.date);
});

Don’t Miss : Display current date and time in HTML using JavaScript

Read Also:  How to call JavaScript function in html?

How to sort an array by date value in JavaScript

Example 1:

const sortedWebsiteList = website_list.sort((a, b) => b.date - a.date)

Example 2:

const sortedWebsiteList = website_list.slice().sort((a, b) => b.date - a.date)

Sorting an array by date in JavaScript

const sortedWebsiteList = [{id: 1, date: 'Mar 12 2022 10:00:00 PM'}, {id: 2, date: 'Mar 8 2022 08:00:00 PM'}];

Example

const sortedWebsiteList = [{id: 1, date: 'Mar 12 2022 10:00:00 PM'}, {id: 2, date: 'Mar 8 20120222 08:00:00 PM'}];
const sortByDate = sortedWebsiteList => {
   const sorter = (a, b) => {
      return new Date(a.date).getTime() - new Date(b.date).getTime();
   }
   sortedWebsiteList.sort(sorter);
};
sortByDate(sortedWebsiteList);
console.log(sortedWebsiteList);

I hope you get an idea about javascript sort by date.
I would like to have feedback on my infinityknow.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.