How To Convert Map Keys To An Array In JavaScript

convert Map Keys to an Array in JavaScript

In this article, I will show you how to convert Map Keys to an array in JavaScript by using the map.keys() method. Most programmers map.keys() to solve this problem, and now let’s learn about it.

Convert Map Keys To An Array In JavaScript

Map.keys() is a built-in method in Javascript that Returns an iterator object with the keys in a map. We can use it to convert Map Keys to an array in JavaScript. Here are two methods that I often use.

Method 1: Use string.replace() method 

Array.from() is used to create an array from a string. We can only use it as Array.from().

Syntax:

Array.from(object, mapFunction, thisValue)

Parameters:

  • object: Indispensable. Is the object you want to convert to an array
  • mapFunction: Optional. It is the function to call on each element.
  • thisValue: Optional. Is the value to use for mapFunction

Example:

let myMap = new Map()
myMap.set('Alma', 20);
myMap.set('Lana', 25);

const myArray = Array.from(myMap.keys());

console.log(myArray); 
console.log(myArray.length);

Output:

['Alma', 'Lana']
2

We see in this example that I have created an array from a Map, and the elements of this array are the keys of the Map. In addition, we can create an array containing only the values ​​of the keys of the Map.

Method 2: Use Spread syntax

Spread syntax (…) is used to copy the elements of an array of an existing object to another array or object. We can use it to pass the map elements through a string you want to understand more about it, follow the example below.

Example:

let myMap = new Map()
myMap.set('Alma', 20);
myMap.set('Lana', 25);

const myArray = [...myMap.keys()];

console.log(myArray); 
console.log(myArray.length);

Output:

['Alma', 'Lana']
2

We see the result returned is the same as when we use from(), but the syntax is shorter. Based on the spread syntax, we can create a new array containing the keys of two different maps.

let myMap = new Map();
myMap.set('Alma', 20);
myMap.set('Lana', 25);

let myMap2 = new Map();
myMap.set('Tom', 20);
myMap.set('John', 25);

const myArray = [...myMap.keys() , ...myMap2];

console.log(myArray); 
console.log(myArray.length);

Output:

['Alma', 'Lana','Tom', 'John']
4

We see that the newly created array has all the keys of two map myMap and myMap2 and the new array has a length of 4.

Summary

In this tutorial, I have shown you how to convert Map Keys to an array in JavaScript. I hope this article will help your program good luck. Thank you for reading!

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *