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().
Array.from(object, mapFunction, thisValue)
- 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
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);
['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.
let myMap = new Map() myMap.set('Alma', 20); myMap.set('Lana', 25); const myArray = [...myMap.keys()]; console.log(myArray); console.log(myArray.length);
['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);
['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.
Maybe you are interested:
- Remove the last element from an array
Name of the university: UTC