js 常见业务数据数组转换操作 时间复杂度降级O(n)的尝试

  1. 提取外层关键数据(如果需要),将双层数组扁平化为单层
  2. 单层再做转换,很容易得到O(n)的实现
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))

posted @ 2022-02-23 22:30  IslandZzzz  阅读(103)  评论(0编辑  收藏  举报