0

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

2 Answers 2

1

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));
Sign up to request clarification or add additional context in comments.

1 Comment

Arrgh... I was so close. OK, thank you!
1
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.