具有Moment(date)元素的数组排序 [英] Sorting of array with Moment(date) elements
问题描述
我有一个数组,其中填充了moment(数据库提供的日期)元素.我正在尝试对数组进行排序,以使第一个元素是最旧的,而最后一个元素是最新的,但是没有成功.
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.
推荐答案
这比您想象的要容易得多. :-)当在作为Moment实例的操作数上使用-
时,它们将被强制转换为数字,即它们的毫秒数(自Epoch以来的值).所以:
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).
我很高兴在那里使用了简洁的箭头功能,因为您已经在代码中使用了ES2015 +功能.
I've happily used concise arrow functions there, since you're already using ES2015+ features in your code.
示例:
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>
这篇关于具有Moment(date)元素的数组排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!