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,
},
,
];
我有一个问题列表,我想根据日期,时刻,从(),属性对它们进行排序。怎么做到这一点?
你可以这样做:
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)
您不必随时解析日期字符串以对数组进行排序。您可以通过排序字符串来完成。
为此你可以使用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)) );