Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

63
Views
Unsure how to sort 2d javascript array by date

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

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

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));
about 4 years ago · Juan Pablo Isaza Report

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!