如何按日期对对象数组进行排序具有特定格式

how to sort array of object by date has specific format

我有包含日期​​格式的对象数组。代码仅适用于订购日期而不适用于月份和年份

我的代码

const bills = [
  {
    name: "ghaith",
    type: "transport",
    date: "12 may 21",
  }, 
  {
    name: "Alex",
    type: "Restaurants",
    date: "15 oct 20",
  }
];

bills.sort((a, b) => b.date < a.date ? 1 : -1)

从上面的评论...

"bills.sort((a, b) => new Date(a.date).getTime() - new Date(b.date).getTime()) ... which of cause works for valid date shorthand formats only ... the OP e.g. did provide originally "12 mai 21" whereas it should be "12 may 21" ... it's fixed/edited already."

const bills = [{
  name: "ghaith",
  type: "transport",
  date: "12 may 21",
}, {
  name: "Alex",
  type: "Restaurants",
  date: "15 oct 20",
}];

console.log(
  bills.sort((a, b) =>
    // new Date(a.date).getTime() - new Date(b.date).getTime()
    // or directly without `getTime` ...
    new Date(a.date) - new Date(b.date)
  )
);
.as-console-wrapper { min-height: 100%!important; top: 0; }

您可以使用以下代码按具有特定格式的日期对对象数组进行排序:

    const bills = [{
      name: "ghaith",
      type: "transport",
      date: "12 may 21",
    }, {
      name: "Alex",
      type: "Restaurants",
      date: "15 oct 20",
    }];


    console.log(
      bills.sort((a, b) => new Date(a.date) - new Date(b.date))
    );