Sort array by date gives unexpected results

前端 未结 2 1828
野的像风
野的像风 2020-12-05 22:52

This will sound as an easy problem but I spent my Sunday trying to figure out what\'s wrong with my implementation described below so I am posting it to SO as a last resort.

2条回答
  •  独厮守ぢ
    2020-12-05 23:26

    let sortedDates = dates.sort(function(a, b){
      return moment(b).format('X')-moment(a).format('X')
    });
    

    Since moment can format valid dates the best way is to use the sort method javascript, so when formatting the date to timestamp, basically you sort by number.

    References:

    http://www.momentjs.com/docs/#/displaying/format

    http://www.w3schools.com/jsref/jsref_sort.asp

提交回复
热议问题