如何根据日期属性对项目列表进行排序?

问题描述 投票:-1回答:2
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,
    },
    ,
];

我有一个问题列表,我想根据日期,时刻,从(),属性对它们进行排序。怎么做到这一点?

javascript momentjs
2个回答
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)

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)) );
© www.soinside.com 2019 - 2024. All rights reserved.