0

I am trying to write an efficient function that merges multiple maps in the following way:

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};

Below is my attempt. I am concerned that my function is not as efficient as it could be. Also, my function does not preserve the order of the elements. How can this be achieved? Thanks!

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]
                )
            );
        }
    };
UofF
  • 33
  • 3

1 Answers1

0

Using Array#reduce iterate over the list of maps. In each iteration, use Object#keys to get the keys of the current element, and iterate over it using Array#forEach to update acc values:

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);
Majed Badawi
  • 27,616
  • 4
  • 25
  • 48