js sort array of objects by date code example

Example 1: javascript sort on objects date

array = [{
  			id: 1, name: "test1", date: "2020-01-05",
			id: 2, name: "test2", date: "2020-01-02"
		}]

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

console.log(array) //array is now sorted by date

Example 2: javascript order array by date

const sortedActivities = activities.sort((a, b) => b.date - a.date)

Example 3: javascript sort array of date

array.sort(function(a,b){
  // Turn your strings into dates, and then subtract them
  // to get a value that is either negative, positive, or zero.
  return new Date(b.date) - new Date(a.date);
});

Example 4: sort array of objects javascript by date

array.sort(function(a,b){
  // Turn your strings into dates, and then subtract them
  // to get a value that is either negative, positive, or zero.
  return new Date(b.date) - new Date(a.date);
});

Example 5: sort date array javascript

const activities = [
  { title: 'Hiking', date: new Date('2019-06-28') },
  { title: 'Shopping', date: new Date('2019-06-10') },
  { title: 'Trekking', date: new Date('2019-06-22') }
]