I have a 2D array in JavaScript where the first row contains date-time strings, and I want to sort all the rows based on the dates in the first row. Here’s an example of my array:
const data = [
['4:23:28 PM', '4:24:01 PM', '4:24:39 PM', '4:26:05 PM'],
[1, 2, 3, 0],
[4, 5, 3, 2]
];
I’ve tried a few approaches, but I’m running into issues. Can someone provide a working solution or suggest how I can achieve this? Also, here’s the expected output after sorting:
const expectedOutput = [
['4:26:05 PM', '4:24:39 PM', '4:24:01 PM', '4:23:28 PM'],
[0, 3, 2, 1],
[2, 3, 5, 4]
];
Thank you in advance for your help!
4
Answers
you first need to convert (map) the date you have in each item to a sortable item … here is the approach I usually used
You can do this in steps:
Here is how it could be done:
Here’s an approach
And a benchmark: