1

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.

2
  • reduce might be a way? Commented Jul 16, 2022 at 19:15
  • @cmgchess it seems flatMap is a more short way, thanks Commented Jul 16, 2022 at 19:23

3 Answers 3

6

You are looking for flatMap:

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

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

console.log(merged)

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.