Sorting nested arrays of objects by date

后端 未结 3 1956
陌清茗
陌清茗 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

    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()
    

提交回复
热议问题