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
JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav
11 min read
Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De
5 min read
React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications
15+ min read
JavaScript Interview Questions and Answers JavaScript (JS) is the most popular lightweight, scripting, and interpreted programming language. JavaScript is well-known as a scripting language for web pages, mobile apps, web servers, and many other platforms. Both front-end and back-end developers need to have a strong command of JavaScript, as
15+ min read
React Tutorial React is a JavaScript Library known for front-end development (or user interface). It is popular due to its component-based architecture, Single Page Applications (SPAs), and Virtual DOM for building web applications that are fast, efficient, and scalable.Applications are built using reusable compon
8 min read
Domain Name System (DNS) DNS is a hierarchical and distributed naming system that translates domain names into IP addresses. When you type a domain name like www.geeksforgeeks.org into your browser, DNS ensures that the request reaches the correct server by resolving the domain to its corresponding IP address.Without DNS, w
8 min read
Introduction to Tree Data Structure Tree data structure is a hierarchical structure that is used to represent and organize data in the form of parent child relationship. The following are some real world situations which are naturally a tree.Folder structure in an operating system.Tag structure in an HTML (root tag the as html tag) or
15+ min read
NodeJS Interview Questions and Answers NodeJS is one of the most popular runtime environments, known for its efficiency, scalability, and ability to handle asynchronous operations. It is built on Chromeâs V8 JavaScript engine for executing JavaScript code outside of a browser. It is extensively used by top companies such as LinkedIn, Net
15+ min read
HTML Interview Questions and Answers HTML (HyperText Markup Language) is the foundational language for creating web pages and web applications. Whether you're a fresher or an experienced professional, preparing for an HTML interview requires a solid understanding of both basic and advanced concepts. Below is a curated list of 50+ HTML
14 min read
What is an API (Application Programming Interface) In the tech world, APIs (Application Programming Interfaces) are crucial. If you're interested in becoming a web developer or want to understand how websites work, you'll need to familiarize yourself with APIs. Let's break down the concept of an API in simple terms.What is an API?An API is a set of
10 min read