Order array of objects by date DESC

Shaun Ericson
Kilo Contributor

I have an array of objects:

var array = [ {date: "2018-08-26T00:00:00Z"}, {date: "2020-08-26T00:00:00Z"}, {date: "2017-08-26T00:00:00Z"} ]

...and trying to reorder the objects in the array by "date" DESC.

I found this post which has a great solution in it, and the solution works with the dates provided in the array from that post: Community Post however if you swap out the array of dates for the ones I need to work with I can't get it to work. Here is a snippet of code from what I am trying to do:

var array = [ {date: "2018-08-26T00:00:00Z"}, {date: "2020-08-26T00:00:00Z"}, {date: "2017-08-26T00:00:00Z"} ]

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

gs.print(array[0].date)

If I run this code against a Node server, it works great. 

I have troubleshot this a lot, so providing the simplest version of what I am trying to solve less all the noise and millions of iterations of attempts. 🙂 Anyone have any idea on how to make this logic work with the dates that I am working with?

Thanks in advance!

 

1 ACCEPTED SOLUTION

Simon Christens
Kilo Sage

I dont think "new Date()" takes "2017-08-26T00:00:00Z" as a valid format.

But it should be possible to sort the array by:

var array = [ {date: "2018-08-26T00:00:00Z"}, {date: "2020-08-26T00:00:00Z"}, {date: "2017-08-26T00:00:00Z"} ]

array.sort(function(a, b) {
  
  var date1 = new GlideDateTime();
	date1.setValueUTC(a.date.replace("T", " ").replace("Z", ""), "yyyy-MM-dd HH:mm:ss");
	
	var date2 = new GlideDateTime();
	
	date2.setValueUTC(b.date.replace("T", " ").replace("Z", ""), "yyyy-MM-dd HH:mm:ss");
	
	if (date1.getValue() < date2.getValue())
		return 1;
	
	if (date1.getValue() > date2.getValue())
		return -1;
	
	return 0;
});

View solution in original post

5 REPLIES 5

@Simon Christensen, appreciate your response and this worked perfectly for me. Thank you!