【问题标题】:merging multiple maps efficiently while preserving order [duplicate]在保持顺序的同时有效地合并多个地图[重复]
【发布时间】:2021-07-04 17:31:01
【问题描述】:

我正在尝试编写一个高效的函数,通过以下方式合并多个地图:

let map1 = { 'A': 2, 'B': 3, 'G': 7 };
let map2 = { 'A': 3, 'B': 5, 'G': 10 };
let map3 = { 'A': 1, 'B': 1, 'G': 1 };
output: map3 = {'A': 6, 'B': 9, 'G':18};

以下是我的尝试。我担心我的功能没有达到应有的效率。另外,我的函数不保留元素的顺序。如何做到这一点?谢谢!

function merge(map1, map2) {
        if (map1 != null && map2 != null) {
            let objects = [map1, map2];
            const merged = objects.reduce((a, obj) => {
                Object.entries(obj).forEach(([key, val]) => {
                    a[key] = (a[key] || 0) + val;
                });
                map2 = a;
                return a;
            }, {});
            return Object.fromEntries(
                Object.entries(merged).sort(
                    (a, b) => b[1] - a[1]
                )
            );
        }
    };

【问题讨论】:

    标签: javascript


    【解决方案1】:

    使用Array#reduce 遍历地图列表。在每次迭代中,使用Object#keys 获取当前元素的键,并使用Array#forEach 对其进行迭代以更新acc 值:

    const 
      map1 = { 'A': 2, 'B': 3, 'G': 7 },
      map2 = { 'A': 3, 'B': 5, 'G': 10 },
      map3 = { 'A': 1, 'B': 1, 'G': 1 };
    
    // group maps in one array
    const merged = [map1, map2, map3]
    // iterate over the array while updating an object
    .reduce((acc, el) => {
      // iterate over current element's keys and update acc
      Object.keys(el).forEach(key => acc[key] = (acc[key] || 0) + el[key]);
      return acc;
    }, {});
    
    console.log(merged);

    【讨论】:

      猜你喜欢
      • 2015-09-24
      • 2015-08-25
      • 1970-01-01
      • 2021-11-22
      • 2019-05-11
      • 2016-07-24
      • 1970-01-01
      • 1970-01-01
      • 2021-03-19
      相关资源
      最近更新 更多