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
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 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
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
How to Convert a Map to JSON String in JavaScript ? A Map is a collection of key-value pairs, where each key is unique. In this article, we will see how to convert a Map to a JSON (JavaScript Object Notation) string in JavaScript. However, JSON.stringify() does not directly support Map objects. Table of ContentUsing Object.fromEntries() MethodUsing A
2 min read
JavaScript Map keys() Method The Map.keys() method is used to extract the keys from a given map object and return the iterator object of keys. The keys are returned in the order they were inserted.Syntax:Map.keys()Parameters:This method does not accept any parameters.Return Value:This returns the iterator object that contains k
3 min read
JavaScript Map entries() Method JavaScript Map.entries() method is used for returning an iterator object which contains all the [key, value] pairs of each element of the map. It returns the [key, value] pairs of all the elements of a map in the order of their insertion. The Map.entries() method does not require any argument to be
4 min read
JavaScript Map Reference JavaScript Map is a collection of elements where each element is stored as a key, value pair. Map objects can hold both objects and primitive values as either key or value. When we iterate over the map object it returns the key, and value pair in the same order as inserted.You can create a JavaScrip
3 min read
How to Iterate over Map Elements in TypeScript ? In TypeScript, iterating over the Map elements means accessing and traversing over the key-value pairs of the Map Data Structure. The Map is nothing but the iterative interface in TypeScript. We can iterate over the Map elements in TypeScript using various approaches that include inbuilt methods and
4 min read