Sorting Rows of a 2D Array in JavaScript Based on Dates in the First Row

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!

>Solution :

Here’s an approach

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

const getDate = (timeString) => {
  const [time, ampm] = timeString.split(' ');
  const [hours, minutes, seconds] = time.split(':').map(Number);
  const adjustedHours = ampm === 'PM' && hours !== 12 ? hours + 12 : hours;
  return new Date(0, 0, 0, adjustedHours, minutes, seconds);
};

const sortedIndices = data[0]
    .map((time, index) => [index, getDate(time)])
    .sort((a, b) => b[1] - a[1])
    .map(([index]) => index);
    
const transformed = data.map((arr) => sortedIndices.map((index) => arr[index]));

console.log(transformed);

Leave a Reply