不确定如何按日期对 2d javascript 数组进行排序

Unsure how to sort 2d javascript array by date

引用 How to sort an object array by date property?,为什么这不起作用?

let arr = [];
arr.push(["07-Mar-2022", "BG76694", "PETE FRAMPTON"]);
arr.push(["07-Mar-2022", "AQ80789", "BARACK OBAMA"]);
arr.push(["08-Mar-2022", "BE39395", "CHEVY CHASE"]);
arr.push(["01-Feb-2022", "AU78617", "GEORGE LUCAS"]);
arr.push(["28-Feb-2022", "BF62132", "GEORGE WASHINGTON"]);
arr.sort((a,b) => new Date(a[0].date) - new Date(b[0].date));
console.log(arr[0][0]);

无论我输入什么日期,输出都是未排序数组第一个元素的日期(在本例中为“2022 年 3 月 7 日”)。我的理解是 sort 对数组进行排序,即。它改变了原来的数组。我希望上面的输出是“01-Feb-2022”(如果我混淆了排序方向,则为“08-Mar-2022”。)

数组元素中没有 date,因为它们是数组。您可以按每个数组的第一项排序,如下所示:

const arr = [];
arr.push(["07-Mar-2022", "BG76694", "PETE FRAMPTON"]);
arr.push(["07-Mar-2022", "AQ80789", "BARACK OBAMA"]);
arr.push(["08-Mar-2022", "BE39395", "CHEVY CHASE"]);
arr.push(["01-Feb-2022", "AU78617", "GEORGE LUCAS"]);
arr.push(["28-Feb-2022", "BF62132", "GEORGE WASHINGTON"]);

arr.sort((a, b) => new Date(a[0]) - new Date(b[0]));

console.log(arr);

Shorthand:

arr.sort(([a], [b]) => new Date(a) - new Date(b));
let arr = [];
arr.push(["07-Mar-2022", "BG76694", "PETE FRAMPTON"]);
arr.push(["07-Mar-2022", "AQ80789", "BARACK OBAMA"]);
arr.push(["08-Mar-2022", "BE39395", "CHEVY CHASE"]);
arr.push(["01-Feb-2022", "AU78617", "GEORGE LUCAS"]);
arr.push(["28-Feb-2022", "BF62132", "GEORGE WASHINGTON"]);
arr.sort((a,b) => new Date(a[0]).getTime() - new Date(b[0]).getTime());
console.log(arr);

使用 getTime() 获取以毫秒为单位的时间,同时您正在访问一个不存在的 属性 'date'