JS sort array by nested child array date values

Hi all,

I have a data set that is a collection of task groups. Each task group has a collection of tasks inside.

My question is, how can I sort the task group array by the child “tasks” due date?

I would like to sort it by the most urgent item (eg) compare to the date right now to the task due date.

Thanks so much in advance!

[
    {
        "name": "a group", 
        "id": "23d72dbc-5c41-4d53-aae0-622049a96450",
        "tasks": [
            {
                "name": "task 1", 
                "dueDateTime": "2022-04-12T05:38:01.367Z",
                "importance": "Normal",
                "id": "695a13eb-a7d8-47f8-8d4f-13e46cab8e53",
                "active": true,
                "complete": false,
                "countdown": "Future"
            },
            {
                "name": "task 2",
                "dueDateTime": "2022-05-12T05:38:01.367Z",
                "importance": "Normal",
                "emailOverdue": true,
                "note": "task message",
                "attachments": [],
                "id": "91dab5d3-dcf8-49c1-90ac-8ad1ba6a2981",
                "active": true,
                "complete": false,
                "countdown": "Future"
            }
        ],
    },
    {
        "name": "Task group 2 (LEAST URGENT)",
        "id": "f53d57f4-b4ac-4236-bffc-0d42b754fbfc",
        "tasks": [
            {
                "name": "task 1",
                "dueDateTime": "2023-05-12T05:38:01.367Z",
                "id": "5a2e310c-54c1-4cb6-82b0-9b1bd920c99c",
                "complete": false,
            },
        ],
    },
    {
        "name": "Task goup 3 (MOST URGENT)",
        "id": "74df1296-aa88-42f7-a297-fb89b818d944",
        "tasks": [
            {
                "name": "task 1",
                "dueDateTime": "2023-05-12T05:38:01.367Z",
                "note": "task message",
                "id": "1788b888-3491-4939-8973-a19b006da3b7",
            },
            {
                "name": "task 2",
                "dueDateTime": "2021-05-12T05:38:01.367Z",
                "id": "35f23aa1-5dda-4a3a-8da8-9926bfed868f",
            }
        ],
    },
]

Ok I think I got it working like this:

 function getMostUrgentTaskTime(tasks)  {
  const itemDueTimes = tasks.map((task) => new Date(task.dueDateTime).getTime());
  const mostUrgentItem = Math.min(...itemDueTimes);
  return new Date(mostUrgentItem).getTime();
}

function sortTasks () {
  return taskGroups.sort((a, b) => {
    const aTask = getMostUrgentTaskTime(a.tasks)
    const bTask = getMostUrgentTaskTime(b.tasks)

    return aTask - bTask
  })

}

yeah i would have said something similar, to sort that dataset for ‘duedates’ using ‘sort’ or comparable methods, well done :slight_smile:

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.