- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Maps in JavaScript takes keys and values array and maps the values to the corresponding keys
Suppose we have two arrays −
const keys = [0, 4, 2, 3, 1]; const values = ["first", "second", "third", "fourth", "fifth"];
We are required to write a JavaScript function that takes in the keys and the values array and maps the values to the corresponding keys.
Therefore, the output should look like −
const map = { 0 => 'first', 4 => 'second', 2 => 'third', 3 => 'fourth', 1 => 'fifth' };
Therefore, let’s write the code for this function −
Example
The code for this will be −
const keys = [0, 4, 2, 3, 1]; const values = ["first", "second", "third", "fourth", "fifth"]; const buildMap = (keys, values) => { const map = new Map(); for(let i = 0; i < keys.length; i++){ map.set(keys[i], values[i]); }; return map; }; console.log(buildMap(keys, values));
Output
The output in the console will be −
Map(5) { 0 => 'first', 4 => 'second', 2 => 'third', 3 => 'fourth', 1 => 'fifth' }
- Related Articles
- The Keys and values method in Javascript
- Mapping values to keys JavaScript
- Split keys and values into separate objects - JavaScript
- Iterate through Object keys and manipulate the key values in JavaScript
- Comparing objects in JavaScript and return array of common keys having common values
- Add values of matching keys in array of objects - JavaScript
- Fetching JavaScript keys by their values - JavaScript
- Extracting Keys and Values from Hash in Perl
- URLSearchParams values & keys() in Node
- Building a Map from 2 arrays of values and keys in JavaScript
- Compare keys & values in a JSON object when one object has extra keys in JavaScript
- Java Program to retrieve the set of all keys and values in HashMap
- How to retrieve windows registry keys and values using PowerShell?
- How to generate child keys by parent keys in array JavaScript?
- JavaScript - Find keys for the matched values as like query in SQL

Advertisements