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 mon 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 mon way.
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 mon 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 mon way.
Share Improve this question asked Jul 16, 2022 at 19:11 Uladzislau KaminskiUladzislau Kaminski 2,2752 gold badges19 silver badges35 bronze badges 2- reduce might be a way? – cmgchess Commented Jul 16, 2022 at 19:15
- @cmgchess it seems flatMap is a more short way, thanks – Uladzislau Kaminski Commented Jul 16, 2022 at 19:23
3 Answers
Reset to default 6You are looking for flatMap:
const arr = [
new Map([[1, 2]]),
new Map([[3, 4]]),
];
const merged = arr.flatMap(e => [...e])
console.log(merged)
.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]);
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]);