Sorting nested arrays of objects by date

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

提交回复
热议问题