Sort nested arrays of objects by date

I am trying to sort an array that looks like this:

var dateGroups = [ [ {age:20, date: Fri Feb 03 2012 14:30:00 GMT+1100 (EST)}, {age:12, date: Fri Feb 03 2012 18:20:00 GMT+1100 (EST)}, {age:18, date: Fri Feb 03 2012 21:43:00 GMT+1100 (EST)} ], [ {age:32, date: Fri Feb 01 2012 10:54:00 GMT+1100 (EST)}, {age:44, date: Fri Feb 01 2012 11:45:00 GMT+1100 (EST)}, ], [ {age:22, date: Fri Feb 05 2012 10:54:00 GMT+1100 (EST)}, {age:22, date: Fri Feb 05 2012 18:22:00 GMT+1100 (EST)}, ] ] 

The objects inside the nested dateGroups arrays are already sorted in ascending order, but I also want to sort the arrays themselves based on grouped dates.

In this case, the array should look like this:

 var dateGroups = [ [ {age:32, date: Fri Feb 01 2012 10:54:00 GMT+1100 (EST)}, {age:44, date: Fri Feb 01 2012 11:45:00 GMT+1100 (EST)}, ], [ {age:20, date: Fri Feb 03 2012 14:30:00 GMT+1100 (EST)}, {age:12, date: Fri Feb 03 2012 18:20:00 GMT+1100 (EST)}, {age:18, date: Fri Feb 03 2012 21:43:00 GMT+1100 (EST)} ], [ {age:22, date: Fri Feb 05 2012 10:54:00 GMT+1100 (EST)}, {age:22, date: Fri Feb 05 2012 18:22:00 GMT+1100 (EST)}, ] ] 

The function used for sorting should also return a new sorted version of dateGroups.

I tried using Underscore.js sortBy() , but I cannot figure out how to sort arrays based on the value of a property inside one of the objects. Is there a way to sort Date objects? Or are they sorted like numbers or letters?

+4
source share
3 answers

According to Underscore.js documentation, you should just write your own iterator for this purpose. Something like that:

 _.sortBy(dateGroups, function(arrayElement) { //element will be each array, so we just return a date from first element in it return arrayElement[0].date.getTime(); }); 
+9
source

You can sort them by passing the custom sort function Array.sort .

 dateGroups.sort(function(a, b) { return b[0].date.getTime() - a[0].date.getTime(); }); 

The user-defined function must return a number less than zero (a comes before b), greater than zero (a comes after b) or zero (a and b are equal).

+4
source

As far as I understand your question, you want to sort the internal groups in order to display the early dates first, and then sort the groups by their first dates. This can be done as follows:

 var sortedDateGroups = dateGroups.map(function(dateGroup) { // sort the inner groups dateGroup.sort(function(a,b) { return a.date.getTime() - b.date.getTime(); }); return dateGroup; }).sort(function(a,b) { // sort the outer groups return a[0].date.getTime() - b[0].date.getTime(); }); 

Of course, this can be done with js underlining in a similar way:

 var sortedDateGroups = _.chain(dateGroups).map(function(dateGroup) { return _.sortBy(dateGroup, function(inner) { return inner.date.getTime(); }); }).sortBy(function(outer) { return outer[0].date.getTime(); }).value() 
+1
source

Source: https://habr.com/ru/post/1013076/


All Articles