I'm trying to split an instance of Map
into separate arrays. An example of the Map
instance I have:
new Map([
["Guatemala", 7],
["Albania", 7],
["Finland", 3],
["Canada", 12],
["Japan", 21],
...
]);
There's more data, but just wanted to show a small sample.
I produced it from the raw data I get from an API in JSON format:
[
{
id: 1,
import_country: "Argentina",
model: "riolet",
make: "Audi",
sold_by: "Huey Bagster",
sale_price: 18643,
},
{
id: 2,
import_country: "China",
model: "MKX",
make: "Lincoln",
sold_by: "Wolf Coller",
sale_price: 16850,
},
{
id: 3,
import_country: "Portugal",
model: "Coupe Quattro",
make: "Audi",
sold_by: "Doroteya McLewd",
sale_price: 13733,
},
]
So I took the import_country
and counted the number of times it appeared and created map
as an instance of Map
.
In order to get the keys and values of map
in separate arrays, I tried the following:
map.forEach(key, value){
country.append(key);
numCountry.append(value);
}
where country
and numCountry
are separate arrays.
My end desired output is:
country = ["Guatemala", "Albania"...] and
numCountry = [7, 7, ...]
If your map is an instance of Map
, then use its keys
and values
methods:
const map = new Map([
["Guatemala", 7],
["Albania", 7],
["Finland", 3],
["Canada", 12],
["Japan", 21],
]);
const countries = [...map.keys()];
const numCountries = [...map.values()];
console.log(countries);
console.log(numCountries);