How to usefor of loop in Javascript
In this approach, we are using a for…of loop, iterate through Map entries. Extract keys and values by destructuring each entry, appending them to separate arrays.
Syntax:
for ( variable of iterableObjectName) {
...
}
Example: In this example we are using the above-explained approach.
const map = new Map([
[1, "HTML"],
[2, "CSS"],
[3, "JavaScript"]
]);
let keys = [];
let values = [];
for (const [key, value] of map) {
keys.push(key);
values.push(value);
}
console.log(keys);
console.log(values);
Output
[ 1, 2, 3 ] [ 'HTML', 'CSS', 'JavaScript' ]
JavaScript Program to Split Map Keys and Values into Separate Arrays
In this article, we are going to learn about splitting map keys and values into separate arrays by using JavaScript. Splitting map keys and values into separate arrays refers to the process of taking a collection of key-value pairs stored in a map data structure and separating the keys and values into two distinct arrays. The map is a data structure that allows you to store pairs of elements, where each element consists of a unique key and an associated value.
There are several methods that can be used to Split map keys and values into separate arrays, which are listed below:
- Using Array from() Method
- Using forEach() Method
- Using Spread Operator
- Using for-of Loop
We will explore all the above methods along with their basic implementation with the help of examples.