1

I have this ES6 map:

Map(6) {"Coratia" => 1, "Korea" =>, "Norway" => 2, "Munich" => 1, "Austrlia" => 1, ...}

I'd like to swap the key and values to make it like this:

 {1 => "Coratia", 1 => "Korea", 2 => "Norway", 1 => "Munich", 1 => "Australia", ...}
1
  • 9
    A map should not have multiple values for the same key like that unless you're hoping for a Map of string, array... in which case you could have something like {1: ["cortia", "Korea", "Munich", "Australia"...], 2: "Norway"} Commented Mar 30, 2019 at 4:09

2 Answers 2

1

Here you have one solution that uses the idea mentioned by CodyKnapp. It uses Array.reduce() to generate the value->key reverse Map.

let myMap = new Map([
   ["Cortia", 1],
   ["Korea", 1],
   ["Norway", 2]
]);

// Generate the reverse Map.

let res = [...myMap.entries()].reduce((acc, [k, v]) =>
{
    acc.has(v) ? acc.set(v, acc.get(v).concat(k)) : acc.set(v, [k]);
    return acc;
}, new Map());

// Log the new generated Map.

res.forEach((v, k) => console.log(`${k} => ${v}`));
.as-console {background-color:black !important; color:lime;}
.as-console-wrapper {max-height:100% !important; top:0;}

Note, as mentioned in the commentaries, that you can't have a Map that will duplicate the same key for multiple different values.

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

Comments

1

ES6 Map when converted into an array looks like so:

 [[key, value], [key, value], [key, value],...]

A two dimensional array.

Demo Outline

  • Assuming that we have a Map with keys and values, make a new empty Map.

  • Iterate through the full Map with for...of loop

  • On each iteration .get() the key/value then assign the value as key and the key as value to the empty Map.

  • The console does not reveal itself by normal means in order to display its content it must iterate through each key/value pair and log them.

let x2D = new Map([
  ['a', 1],
  ['b', 2],
  ['c', 3],
  ['d', 4],
  ['e', 5]
]);

let d2X = new Map();

for (let [key, value] of x2D) {
  let v = x2D.get(key);
  d2X.set(v, key);
}

for (let [k, v] of d2X) {
  console.log('[' + k + ', ' + v + ']');
}

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.