const questions = [
{
"_id" : ObjectId("5bbe4c6d5eca146adc895fa4"),
"title" : "How to Toggle between adding and removing Ajax text",
"date" : "2018-10-10T22:01:01+03:00",
"questionerId" : "5bbda46a433ced65ac7c4699",
"voteNumber" : 0,
},
,
];
我有一个问题列表,我想根据日期,moment.from(),属性进行排序。如何做到这一点?
答案 0 :(得分:0)
您无需解析带有时间的日期字符串即可对数组进行排序。您只需对字符串进行排序即可。
为此,您可以使用f.e. String.prototype.localeCompare。
const questions = [{
"_id" : "5bbe4c6d5eca146adc895fa4",
"title" : "How to Toggle between adding and removing Ajax text",
"date" : "2018-10-10T22:01:01+03:00",
"questionerId" : "5bbda46a433ced65ac7c4699",
"voteNumber" : 0,
},
{
"_id" : "5bbe4c6d5eca146adc895fa4",
"title" : "How to Toggle between adding and removing Ajax text",
"date" : "2018-10-11T22:01:01+03:00",
"questionerId" : "5bbda46a433ced65ac7c4699",
"voteNumber" : 0,
},{
"_id" : "5bbe4c6d5eca146adc895fa4",
"title" : "How to Toggle between adding and removing Ajax text",
"date" : "2018-10-09T22:01:01+03:00",
"questionerId" : "5bbda46a433ced65ac7c4699",
"voteNumber" : 0,
}];
console.log( questions.sort((a, b) => b.date.localeCompare(a.date)) );
答案 1 :(得分:0)
您可以这样操作:
questions.sort((a, b) => new Date(a.date) - new Date(b.date))
但是,我建议在实际排序之前将所有日期字符串转换为Date实例:
questions
.map(q => ({ ...q, date: new Date(q.date) }))
.sort((a, b) => a.date - b.date)