DEV Community

Cover image for How to convert a Map to an Array in JavaScript?
MELVIN GEORGE
MELVIN GEORGE

Posted on • Originally published at melvingeorge.me

How to convert a Map to an Array in JavaScript?

Originally posted here!

To convert the Map data structure to an Array, you can use the from() method from the global Array object in JavaScript.

TL;DR

// Initialise Map to hold roll number
// associated with students name
const rollNumToName = new Map();

// set some values to map
rollNumToName.set(1, "John Doe").set(2, "Lily Roy");

// convert map to array using
// the Array.from() method
const rollNumToNameArr = Array.from(rollNumToName);

console.log(rollNumToNameArr);

/*
OUTPUT:
-------

[
    [1, "John Doe"],
    [2, "Lily Roy"]
]

*/
Enter fullscreen mode Exit fullscreen mode

For example, let's say we want to hold all the roll numbers of students and associate them with the student's name.

So a better data structure to use here is to use the Map data structure in JavaScript.

First, let's initialize a map called rollNumToName like this,

// Initialise Map to hold roll number
// associated with students name
const rollNumToName = new Map();
Enter fullscreen mode Exit fullscreen mode

Now let's add some values using the set() method from the rollNumToName map.

It can be done like this,

// Initialise Map to hold roll number
// associated with students name
const rollNumToName = new Map();

// set some values to map data structure
rollNumToName.set(1, "John Doe").set(2, "Lily Roy");
Enter fullscreen mode Exit fullscreen mode

Now, We have a valid Map data structure.

To convert the rollNumToName map to an array we can use the Array.from() method and pass the rollNumToName map as an argument to the function. The method returns a new array.

It can be done like this,

// Initialise Map to hold roll number
// associated with students name
const rollNumToName = new Map();

// set some values to map data structure
rollNumToName.set(1, "John Doe").set(2, "Lily Roy");

// convert map to array using
// the Array.from() method
const rollNumToNameArr = Array.from(rollNumToName);
Enter fullscreen mode Exit fullscreen mode

Now if we log the output of the rollNumToNameArr array we can see that the rollNumToName map data structure is converted to an array.

It will look like this,

// Initialise Map to hold roll number
// associated with students name
const rollNumToName = new Map();

// set some values to map data structure
rollNumToName.set(1, "John Doe").set(2, "Lily Roy");

// convert map to array using
// the Array.from() method
const rollNumToNameArr = Array.from(rollNumToName);

console.log(rollNumToNameArr);

/*
OUTPUT:
-------

[
    [1, "John Doe"],
    [2, "Lily Roy"]
]

*/
Enter fullscreen mode Exit fullscreen mode
  • Each value in the map is now converted to a nested array inside the main array.

See the above code live in codesandbox.

That's all 😃!

Feel free to share if you found this useful 😃.


Top comments (0)