Sorting nested arrays of objects by date

后端 未结 3 1950
陌清茗
陌清茗 2020-12-10 08:00

I\'m 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:          


        
相关标签:
3条回答
  • 2020-12-10 08:50

    You can sort them by passing a custom sort function to Array.sort.

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

    The custom function needs to return a number less than zero (a comes before b), greater than zero (a comes after b) or zero (a and b are equal).

    0 讨论(0)
  • 2020-12-10 08:50

    As far as I understand your question, you want to sort the inner groups so that the early dates will be displayed first and then sort the groups by their first dates. This could be done like this:

    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 could be done with underscore js in a similar fashion:

    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()
    
    0 讨论(0)
  • 2020-12-10 08:52

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

    _.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();
    });
    
    0 讨论(0)
提交回复
热议问题