1. 程式人生 > 其它 >js 格式化雙層陣列使得時間複雜度為O(n)的嘗試

js 格式化雙層陣列使得時間複雜度為O(n)的嘗試

格式化雙層陣列使得時間複雜度為O(n)的嘗試

  1. 提取關鍵資料,將雙層陣列扁平化為單層
  2. 單層再做轉換
const infos = [
    {
        time: '2022-02-21',
        data: [{
            Duration: 22,
            Spec: "h264"
        },
        {
            Duration: 33,
            Spec: "h265_hd"
        },
        {
            Duration: 44,
            Spec: "h264_4k"
        }]
    },
    {
        time: '2022-02-22',
        data: [{
            Duration: 55,
            Spec: "h264"
        },
        {
            Duration: 66,
            Spec: "h265_hd"
        },
        {
            Duration: 77,
            Spec: "h264_4k"
        }]
    }
]

const _map = list => list
    .reduce((prev, cur) => prev.data.concat(cur.data))
    .reduce((total, { Duration, Spec }) => Object.assign(total, { [Spec]: (total[Spec] || []).concat(Duration) }), {})
const _list = map => Object.entries(map).map(([name, data]) => ({ name, data }))
_list(_map(infos))