Sorting of array with Moment(date) elements

余生长醉 提交于 2020-02-03 06:30:48

问题


I have an array that is populated with moment(Date provided by the database) elements. I am trying to sort the array so that the first element is the oldest and the last element is the newest, but with no success.

     for (let item of items) {

            dates.push(moment(item.created));
          }
          dates.sort(function(a,b){
            var da = new Date(a).getTime();
            var db = new Date(b).getTime();

            return da < db ? -1 : da > db ? 1 : 0
          });
    }
  console.log(dates);

This always prints the current time times number of elements.


回答1:


It's much easier than you think. :-) When you use - on a operands that are Moment instance, they're coerced to numbers, which are their milliseconds-since-the-Epoch value. So:

dates.sort((a, b) => a - b);

...sorts them ascending (earliest dates first), and

dates.sort((a, b) => b - a;

...sorts them descending (latest dates first).

I've happily used concise arrow functions there, since you're already using ES2015+ features in your code.

Example:

let dates = [
  moment("2017-01-12"),
  moment("2018-01-12"),
  moment("2017-07-12"),
  moment("2016-07-30")
];
dates.sort((a, b) => a - b);
console.log(dates);

dates = [
  moment("2017-01-12"),
  moment("2018-01-12"),
  moment("2017-07-12"),
  moment("2016-07-30")
];
dates.sort((a, b) => b - a);
console.log(dates);
.as-console-wrapper {
  max-height: 100% !important;
}
The built-in Stack Snippets console shows Moment instances by calling toString, which shows is the ISO date string. But they're Moment instances (you can see that in the browser's real console).
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>


来源:https://stackoverflow.com/questions/53264492/sorting-of-array-with-momentdate-elements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!