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.

Javascript
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.

Similar Reads

Approach 1: Using Array from() Method

In this approach, we are using Array.from() to transform keys and values into separate arrays. This facilitates the independent handling of keys and values for subsequent operations....

Approach 2: Using forEach() Method

In this approach, we are Iterate through Map using forEach(). Extract keys and values separately during iteration, pushing them into separated arrays....

Approach 3: Using Spread Operator

In this approach, we are using the spread operator to expand Map entries into an array. Employ .map() to extract keys and values separately,...

Approach 4: Using for of loop

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....

Using Array.prototype.reduce() with destructuring

Using `Array.prototype.reduce()` with destructuring, the code iterates through the map, extracting keys and values into separate arrays. It accumulates these arrays in the reducer function, returning them as the result....