An algorithm problem of converting an array to a tree?

< H2 > Source data < / H2 >
[
    {id: 1, matter: "xxx", current: "2018-10-31 09:30:00", photo: ["xxx", "xxx"]},
    {id: 2, matter: "xxx", current: "2018-10-31 11:30:00", photo: ["xxx", "xxx"]},
    {id: 3, matter: "xxx", current: "2018-10-30 08:47:00", photo: ["xxx", "xxx"]}
]
< H2 > processed data < / H2 >

the outer array is sorted by date, the later the more advanced, and the inner array is sorted by time, the earlier the earlier, the earlier the earlier.

[
    {
        date: "2018-10-31",
        list: [
            {
                time: "9:30",
                matter: "xxx",
                photo: ["xxx", "xxx"]
            },
            {
                time: "11:30",
                matter: "xxx",
                photo: ["xxx", "xxx"]
            }
        ]
    }
    {
        date: "2018-10-30",
        list: [
            {
                time: "08:47",
                matter: "xxx",
                photo: ["xxx", "xxx"]
            }
        ]
    }
]

come to the Great God

Oct.07,2021

first aggregate by date, then sort the list in each date, and then sort the whole large array:

Array.from(
  arr.reduce((m, x) => {
    const [date, time] = x.current.split(' ')
    const list = m.get(date) || []
    list.push({ time: time.slice(0, -3), matter: x.matter, photo: x.photo })
    return m.set(date, list)
  }, new Map())
)
.map(([date, list]) => ({ date, list: list.sort((a, b) => a.time > b.time ? 1 : a.time < b.time ? -1 : 0) }))
.sort((a, b) => a.date > b.date ? -1 : a.date < b.date ? 1 : 0)
Menu