Home > Enterprise >  JS merge Array of the Maps to a single Map
JS merge Array of the Maps to a single Map

Time:07-17

I have a structure of

Array(4) [Map(1),Map(1),Map(1),Map(1)]

All keys are different there. I am trying find the common way to merge it in one Map.

I know the way for two Maps:

let merged = new Map([...first, ...second])

But for this solution I need more common way.

CodePudding user response:

.map each map to its entries, then flatten the array of arrays of entries to just a single array of entries, then turn that into a Map.

const arr = [
  new Map([[1, 2]]),
  new Map([[3, 4]]),
];

const merged = new Map(
  arr.map(
    map => [...map]
  ).flat()
);
console.log([...merged]);

CodePudding user response:

You are looking for flatMap:

const arr = [
  new Map([[1, 2]]),
  new Map([[3, 4]]),
];

const merged = arr.flatMap(e => [...e])

console.log(merged)

CodePudding user response:

You can use array#reduce to merge multiple Map.

maps.reduce((r, map) => new Map([...r, ...map]), new Map())

const map1 = new Map();
map1.set('a', 1);
const map2 = new Map();
map2.set('b', 2);
const map3 = new Map();
map3.set('c', 3);

const maps = [map1, map2, map3],
      merged = maps.reduce((r, map) => new Map([...r, ...map]), new Map());
console.log([...merged]);

  • Related