我有一个数组,其中填充了moment(数据库提供的日期)元素。我正在尝试对数组进行排序,以使第一个元素是最旧的,而最后一个元素是最新的,但是没有成功。
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);
这总是打印当前时间乘以元素数。
答案 0 :(得分:2)
这比您想象的要容易得多。 :-)当您在Moment实例的操作数上使用-
时,它们将被强制转换为数字,即从Epoch开始的毫秒数。所以:
dates.sort((a, b) => a - b);
...对它们进行升序排序(最早的日期在前),并且
dates.sort((a, b) => b - a;
...对它们进行降序排序(最新日期在前)。
我很高兴在那里使用了简洁的箭头功能,因为您已经在代码中使用了ES2015 +功能。
示例:
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>