[英]How to sort an array on dates with data using JavaScript?
我有一个数组,其中包含日期和其他一些数据。 我想通过使用日期对该数组进行排序。 我该怎么办? 我不知道。 请帮帮我。 。
这是我的数组=>
0:{_id: "01-11-2017", CommentCount: 221, Likecount: 141, Followcount: 0, Unfollowcount: 116}
1:{_id: "27-10-2017", CommentCount: 235, Likecount: 495, Followcount: 802, Unfollowcount: 98}
2:{_id: "28-10-2017", CommentCount: 232, Likecount: 52, Followcount: 0, Unfollowcount: 799}
3:{_id: "29-10-2017", CommentCount: 236, Likecount: 52, Followcount: 0, Unfollowcount: 611}
4:{_id: "30-10-2017", CommentCount: 233, Likecount: 58, Followcount: 0, Unfollowcount: 0}
5:{_id: "31-10-2017", CommentCount: 240, Likecount: 175, Followcount: 0, Unfollowcount: 0}
预期产量=>
0:{_id: "27-10-2017", CommentCount: 235, Likecount: 495, Followcount: 802, Unfollowcount: 98}
1:{_id: "28-10-2017", CommentCount: 232, Likecount: 52, Followcount: 0, Unfollowcount: 799}
2:{_id: "29-10-2017", CommentCount: 236, Likecount: 52, Followcount: 0, Unfollowcount: 611}
3:{_id: "30-10-2017", CommentCount: 233, Likecount: 58, Followcount: 0, Unfollowcount: 0}
4:{_id: "31-10-2017", CommentCount: 240, Likecount: 175, Followcount: 0, Unfollowcount: 0}
5:{_id: "01-11-2017", CommentCount: 221, Likecount: 141, Followcount: 0, Unfollowcount: 116}
首先,您需要将日期字符串解析为实际的Date
对象。 之后,您可以根据需要对其进行排序:
const inputs = [ {_id: "01-11-2017", CommentCount: 221, Likecount: 141, Followcount: 0, Unfollowcount: 116}, {_id: "27-10-2017", CommentCount: 235, Likecount: 495, Followcount: 802, Unfollowcount: 98}, {_id: "28-10-2017", CommentCount: 232, Likecount: 52, Followcount: 0, Unfollowcount: 799}, {_id: "29-10-2017", CommentCount: 236, Likecount: 52, Followcount: 0, Unfollowcount: 611}, {_id: "30-10-2017", CommentCount: 233, Likecount: 58, Followcount: 0, Unfollowcount: 0}, {_id: "31-10-2017", CommentCount: 240, Likecount: 175, Followcount: 0, Unfollowcount: 0} ]; const results = inputs.sort((a, b) => getDate(a._id) - getDate(b._id)); function getDate(s) { const parts = s.split('-'); return new Date(parts.pop(), parts.pop() - 1, parts.pop()); } console.log(results);
请注意,仅通过Arrow function
,此解决方案仅适用于现代浏览器。
JavaScript不支持您的Date格式,因此您必须先将其反转,然后再将其发送到Date构造函数
console.log(arr.sort(function(a,b) {
return new Date(a._id.split('-').reverse().join('-')).getTime() - new Date(b._id.split('-').reverse().join('-')).getTime()
}))
这样可以解决问题
您可以使用类似这样的内容:
my_array.sort(function(a,b) {
return new Date(a._id.split("-").inverse().join("-")).getTime() - new Date(b._id.split("-").inverse().join("-")).getTime()
});
排序功能行为:
可选的。 定义替代排序顺序的函数。 函数应根据参数返回负,零或正值,例如:function(a,b){return ab}当sort()方法比较两个值时,它将这些值发送到compare函数,并且根据返回的值(负,零,正)对值进行排序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.