JavaScript Program to Split Map Keys and Values into Separate Arrays
Last Updated :
17 Jul, 2024
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.
Several methods can be used to Split map keys and values into separate arrays, which are listed below:
We will explore all the above methods along with their basic implementation with the help of examples.
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.
Syntax:
let keys = Array.from(map.keys());
let values = Array.from(map.values());
Example: In this example, we are using Array.form() method to separate keys and values from our given map.
JavaScript
const map = new Map([
["India", 1],
["USA", 2],
["Russia", 3],
["Canada", 4]
]);
let keys = Array.from(map.keys());
let values = Array.from(map.values());
console.log("Keys are :", keys);
console.log("Values are :", values);
// Nikunj Sonigara
OutputKeys are : [ 'India', 'USA', 'Russia', 'Canada' ]
Values are : [ 1, 2, 3, 4 ]
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.
Syntax:
language.forEach((value, key) => {
keys.push(key);
values.push(value);
});
Example: In this approach we are using the above-explained approach.
JavaScript
const language = new Map([
["HTML", 1],
["CSS", 2],
["JavaScript", 3]
]);
let keys = [];
let values = [];
language.forEach((value, key) => {
keys.push(key);
values.push(value);
});
console.log(keys);
console.log(values);
Output[ 'HTML', 'CSS', 'JavaScript' ]
[ 1, 2, 3 ]
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,
Syntax:
let entries = [...map.entries()];
let keys = entries.map(([key, value]) => key);
let values = entries.map(([key, value]) => value);
Example: In this example, a Map contains cricket player names and their respective jersey number. Using the spread operator, convert Map entries to an array. Extract keys (player names) and values (jersey number) separately using .map()
JavaScript
const map = new Map([
["Virat kohli", 18],
["Rohit sharma", 45],
["M.s Dhoni", 7]
]);
let entries = [...map.entries()];
let keys = entries.map(([key, value]) => key);
let values = entries.map(([key, value]) => value);
console.log(keys);
console.log(values);
Output[ 'Virat kohli', 'Rohit sharma', 'M.s Dhoni' ]
[ 18, 45, 7 ]
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.
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' ]
Approach 5: 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.
Example:
JavaScript
let map = new Map([['a', 1], ['b', 2], ['c', 3]]);
let [keysArray, valuesArray] = Array.from(map).reduce((acc, [key, value]) => {
acc[0].push(key);
acc[1].push(value);
return acc;
}, [[], []]);
console.log(keysArray); // ['a', 'b', 'c']
console.log(valuesArray); // [1, 2, 3]
Output[ 'a', 'b', 'c' ]
[ 1, 2, 3 ]
Approach 6: Using Spread Operator and map()
Using the spread operator and map() to split a Map involves converting the map's keys and values to arrays. The spread operator creates arrays from the map's keys and values iterators, efficiently separating them into distinct arrays.
Example:
JavaScript
let myMap = new Map([
['a', 1],
['b', 2],
['c', 3]
]);
let keys = [...myMap.keys()];
let values = [...myMap.values()];
console.log(keys);
console.log(values);
Output[ 'a', 'b', 'c' ]
[ 1, 2, 3 ]
Approach 7: Using Object.fromEntries() and Object.keys() / Object.values()
In this approach, we utilize Object.fromEntries() to convert the map into an object, and then use Object.keys() and Object.values() to extract the keys and values separately. This method leverages the transformation capabilities of objects in JavaScript to achieve the desired result.
Syntax
let obj = Object.fromEntries(map);
let keys = Object.keys(obj);
let values = Object.values(obj);
Example: In this example, we first convert the map into an object using Object.fromEntries(). Then, we extract the keys and values from the object using Object.keys() and Object.values() respectively.
JavaScript
const map = new Map([
["Germany", 1],
["France", 2],
["Italy", 3],
["Spain", 4]
]);
// Convert Map to Object
let obj = Object.fromEntries(map);
// Extract keys and values from Object
let keys = Object.keys(obj);
let values = Object.values(obj);
console.log("Keys are:", keys);
console.log("Values are:", values);
OutputKeys are: [ 'Germany', 'France', 'Italy', 'Spain' ]
Values are: [ 1, 2, 3, 4 ]
Similar Reads
How to Add a key/value Pair to Map in JavaScript ?
This article will demonstrate how we can add a key-value pair in the JavaScript map. JavaScript Map is a collection of key-value pairs in the same sequence they are inserted. These key values can be of primitive type or the JavaScript object. All methods to add key-value pairs to the JavaScript Map:
3 min read
Convert 2D Array to Object using Map or Reduce in JavaScript
Converting a 2D array to an object is a common task in JavaScript development. This process involves transforming an array where each element represents a key-value pair into an object where keys are derived from one dimension of the array and values from another. Problem Description:Given a 2D arra
2 min read
How to get the Value by a Key in JavaScript Map?
JavaScript Map is a powerful data structure that provides a convenient way to store key-value pairs and retrieve values based on keys. This can be especially useful when we need to associate specific data with unique identifiers or keys.Different Approaches to Get the Value by a Key in JavaScript Ma
3 min read
How To Convert Map Keys to an Array in JavaScript?
Here are the various methods to convert Map keys to an array in JavaScript1. Using array.from() MethodThe Array.from() method in JavaScript converts Map keys to an array by using 'Array.from(map.keys())'. JavaScriptlet map = new Map().set('GFG', 1).set('Geeks', 2); let a = Array.from(map.keys()); co
2 min read
How to Convert an Array of Objects to Map in JavaScript?
Here are the different methods to convert an array of objects into a Map in JavaScript1. Using new Map() ConstructorThe Map constructor can directly create a Map from an array of key-value pairs. If each object in the array has a specific key-value structure, you can map it accordingly.JavaScriptcon
3 min read
How to convert a map to array of objects in JavaScript?
A map in JavaScript is a set of unique key and value pairs that can hold multiple values with only a single occurrence. Sometimes, you may be required to convert a map into an array of objects that contains the key-value pairs of the map as the values of the object keys. Let us discuss some methods
6 min read
What is JavaScript Map and how to use it ?
What is Map?A Map in JavaScript is a collection of key-value pairs where keys can be any data type. Unlike objects, keys in a Map maintain insertion order. It provides methods to set, get, delete, and iterate over elements efficiently, making it useful for data storage and retrieval tasks.Syntaxnew
2 min read
How to convert a Map into a Set in JavaScript?
Map and Set in JavaScript are special kind of data structures that holds only the unique data. There will be no duplicate data stored in them. Maps store data in the form of key-value pairs, while the Sets store in the form of values only. In some scenarios, you need to convert a Map into a Set, the
4 min read
Map to Array in JavaScript
In this article, we will convert a Map object to an Array in JavaScript. A Map is a collection of key-value pairs linked with each other. The following are the approaches to Map to Array conversion: Methods to convert Map to ArrayUsing Spread Operator (...) and Array map() MethodUsing Array.from() M
3 min read
How to convert a Set to Map in JavaScript?
A Set is a collection of unique values. It stores only the data in the form of values while a Map can store the data in the form of key-value pairs. These are the different ways of converting a Set to a Map in JavaScript: Table of Content Using the Array.from() methodUsing the Spread Operator with m
3 min read