
- Javascript Basics Tutorial
- Javascript - Home
- Javascript - Overview
- Javascript - Syntax
- Javascript - Enabling
- Javascript - Placement
- Javascript - Variables
- Javascript - Operators
- Javascript - If...Else
- Javascript - Switch Case
- Javascript - While Loop
- Javascript - For Loop
- Javascript - For...in
- Javascript - Loop Control
- Javascript - Functions
- Javascript - Events
- Javascript - Cookies
- Javascript - Page Redirect
- Javascript - Dialog Boxes
- Javascript - Void Keyword
- Javascript - Page Printing
- JavaScript Objects
- Javascript - Objects
- Javascript - Number
- Javascript - Boolean
- Javascript - Strings
- Javascript - Arrays
- Javascript - Date
- Javascript - Math
- Javascript - RegExp
- Javascript - HTML DOM
- JavaScript Advanced
- Javascript - Error Handling
- Javascript - Validations
- Javascript - Animation
- Javascript - Multimedia
- Javascript - Debugging
- Javascript - Image Map
- Javascript - Browsers
- JavaScript Useful Resources
- Javascript - Questions And Answers
- Javascript - Quick Guide
- Javascript - Functions
- Javascript - Resources
Building a Map from 2 arrays of values and keys in JavaScript
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. The output should be −
const map = { 0 => 'first', 4 => 'second', 2 => 'third', 3 => 'fourth', 1 => 'fifth' };
Example
Following is the code −
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
This will produce the following output in console −
Map(5) { 0 => 'first', 4 => 'second', 2 => 'third', 3 => 'fourth', 1 => 'fifth' }
- Related Articles
- Building frequency map of all the elements in an array JavaScript
- The Keys and values method in Javascript
- Maps in JavaScript takes keys and values array and maps the values to the corresponding keys
- JavaScript map value to keys (reverse object mapping)
- Extracting Keys and Values from Hash in Perl
- How to convert Map keys to an array in JavaScript?
- Mapping values to keys JavaScript
- Split keys and values into separate objects - JavaScript
- Building an array from a string in JavaScript
- Fetching JavaScript keys by their values - JavaScript
- How to map keys to values for an individual field in a MySQL select query?
- Add values of matching keys in array of objects - JavaScript
- Compare keys & values in a JSON object when one object has extra keys in JavaScript
- How to create Python dictionary from list of keys and values?
- JavaScript: How to map array values without using "map" method?

Advertisements