5
110

JavaScript: How To Convert Map Values To Array

Reading Time: 2 minutes

To convert Map Values to Array in JavaScript, there are 3 main methods that are 1 or 2 liner code. They will return the values in an array in the same order during the creation of Map.

Methods to Convert Map Values to Array

  • Array.from() Method
  • Spread Operator/Syntax (...) Method
  • Array.prototype.forEach() Method

The first 2 methods will make use of Map.prototype.values() method from Map built-in object to get an iterator object holding onto the values in insertion order.

Array.from() Method

Array.from() is a static method that will create a new array shallow copying the objects from any iterable objects including the return object from Map.prototype.values(). This method is easy to use if all datatype of Values are primitive.

In the example below, we will pass in the values iterable, then the result will be a new array containing all values in the same order.

const ageMap = new Map([
  ['Person1', 11],
  ['Person2', 33],
  [10000001, 11]
]);

const result = Array.from(ageMap.values());

console.log(result);
// [11, 33, 11]

Spread Operator/Syntax (...) Method

Base on the official documentation of Spread Syntax, we can see that it can expand any iterable. Thus, we can make use of its mechanism to spread out into an array object.

In the example below, we spread the Map values iterable object into an array.

const ageMap = new Map([
  ['Person1', 11],
  ['Person2', 33],
  [10000001, 11]
]);

const result = [...ageMap.values()];

console.log(result);
// [11, 33, 11]

Array.prototype.forEach() Method

From this guide, we know that forEach() will not return any result. Hence, we will create a new array before executing the method.

In the example below, we will push the data in every iteration to the result array.

const ageMap = new Map([
  ['Person1', 11],
  ['Person2', 33],
  [10000001, 11]
]);

const result = [];
ageMap.forEach((value, key) => result.push(value));

console.log(result);
// [11, 33, 11]

Conclusion

We look into the 3 methods of converting Map Values to array in JavaScript.

Array.from() and the spread operator are the easiest to implement when the datatype inside Map Values are all primitive type.

Array.prototype.forEach() method will be good if you want to perform some operation like deep cloning or other operation every iteration with the value.

Show Comments

No Responses Yet

Leave a Reply