Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
129 views
in Technique[技术] by (71.8m points)

javascript - Sorting nested arrays of objects by date

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: 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 dateGroups' nested arrays are already sorted in ascending order, but I also want to sort the arrays themselves based on the grouped dates.

In this case the array should then 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 to sort should also return the new sorted version of dateGroups.

I've tried using Underscore.js's sortBy() function but I can't figure out how to sort the arrays based on the value of a property inside one of the objects. Is there a specific way to sort Date objects? Or are they sorted in the same way as numbers or letters?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...