0

I would like to flatten an array of maps (for example the one in the screenshot).

In the screenshot it's an array of length 2, but this could be an array of length n.

enter image description here

The end result I would like to achieve is to only keep the Maps and remove the array in which the maps are located now.

enter image description here

Anyone knows a solution for this problem? Thank you

I tried the solutions proposed in Simplest way to merge ES6 Maps/Sets? but that did not resolve my specific problem.

UPDATE: The problem was solved by following code:

let tmpArray = [];
myStartingArray.forEach((el) => {
  tmpArray = tmpArray.concat(el.entries());
});

let myMap = new Map();
tmpArray.forEach((d) => {
  myMap.set(d.key, d.value);
});
Dave Newton
  • 158,873
  • 26
  • 254
  • 302
Simke Nys
  • 72
  • 1
  • 9
  • By "flatten", you mean "merge"? – Bergi Dec 27 '21 at 15:49
  • I'm not quite sure if it is a merge. If I would do the same for a regular array I could run this code: [].concat.apply([], myArray) and it would flatten it. Does not work for array of maps. My end result is a single array item with all the maps combined. So for the example: I have an array of length 2 myArray[0] has 1 map entrie and myArray[1] has 3 maps entries. The output should have: outArray[0] with 4 map entries – Simke Nys Dec 27 '21 at 15:51
  • Why do you want to get back an array containing a single map (instead of just a single map)? – Bergi Dec 27 '21 at 15:55
  • do you have some data in text from and the wanted result of it? – Nina Scholz Dec 27 '21 at 16:06
  • @Bergi a single map would be fine as well – Simke Nys Dec 27 '21 at 16:27
  • @SimkeNys you might get better results on SO if you provide a code-sample which sets up your case and what you did which didn't work, e.g. if `const initial = [new Map([['key-a' ,'val-a']]), new Map([['key-b', 'val-b']])];` then looks like you want `initial.reduce((accumulator, item) => new Map([...accumulator, ...item]))` which is `Map(2) {'key-a' => 'val-a', 'key-b' => 'val-b'}` – Paul S. Dec 27 '21 at 16:36
  • @SimkeNys The duplicate does show how create a single map from an array of maps. Can you please [edit] your question to include the code that you tried and how it didn't work? – Bergi Dec 27 '21 at 17:16
  • Answers should be added as an answer and not edited into the question. Marking an answer as "accepted" is how SO indicates a question has been resolved (e.g., not tagging the question title). – Dave Newton Dec 28 '21 at 07:36
  • @DaveNewton there is no answer, I found it myself and wanted to share it for if somebody else had the same issue + my question was closed the instance it was openend so nobody could answer – Simke Nys Dec 28 '21 at 08:53
  • It says right there the problem was solved; that's an answer. My point is that in the future please consider not putting an answer in the question. – Dave Newton Dec 28 '21 at 14:52

0 Answers0