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