admin管理员组文章数量:1338198
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.
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.
Share asked Nov 12, 2018 at 14:41 John VJohn V 5,06716 gold badges44 silver badges68 bronze badges2 Answers
Reset to default 22It'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./ajax/libs/moment.js/2.22.2/moment.min.js"></script>
You can use it like this with moment
dates.sort((a, b) => moment(a.date) - moment(b.date))
本文标签: javascriptSorting of array with Moment(date) elementsStack Overflow
版权声明:本文标题:javascript - Sorting of array with Moment(date) elements - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743529041a2498718.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论