Home > front end >  Unsure how to sort 2d javascript array by date
Unsure how to sort 2d javascript array by date

Time:03-09

Referencing How to sort an object array by date property?, why doesn't this work?

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]);

It doesn't matter what dates I enter, the output is the date from the first element of the unsorted array (in this case "07-Mar-2022"). My understanding is that sort sorts the array in place, ie. it changes the original array. I would expect the output in the above to be "01-Feb-2022" (or else "08-Mar-2022" if I have the sort direction confused.)

CodePudding user response:

There's no date in the array elements as they are arrays. You can sort by the first item of each array as follows:

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));

CodePudding user response:

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);

use getTime() to get the time in milliseconds also you are accessing a property 'date' that doesn't exist

  • Related