Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

best way to join map keys/values comma separated

I have a map that looks like (it's not constant and there could be more subarrays)

var mMp=    new Map([
    [ "A", [1, "r"] ],
    [ "B", [2, "d "]]
    ]);

I am trying to get to:

var ks = "A, B"
var vs1 = "1, 2"
var vs2 = "r, d"

I could do

mMp.forEach( (val, key) => {.....};

where I add the stuff manually, but I'd have to check for the last value. I also thought about

Array.from(mMp.keys()).join(", ");

but that also would not help with the values, i guess. And it's less efficient, although I'm not too worried about efficiency here.

What's the best way I can get those 3 sets for strings? Thank you!

like image 711
solar apricot Avatar asked Jan 30 '23 08:01

solar apricot


1 Answers

Array.from is indeed the way to go. For the values, use .values() instead of .keys() and the callback:

var mMp = new Map([
  ["A", [1, "r"]],
  ["B", [2, "d"]],
  // …
]);
var ks = Array.from(mMp.keys()).join(", "); // "A, B"
var vs1 = Array.from(mMp.values(), v => v[0]).join(", "); // "1, 2"
var vs2 = Array.from(mMp.values(), v => v[1]).join(", "); // "r, d"

If you have value arrays of arbitrary lengths, use a loop to create all your vs arrays.

like image 195
Bergi Avatar answered Jan 31 '23 23:01

Bergi