Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Building a Map from 2 arrays of values and keys in JavaScript
In JavaScript, you can create a Map from two separate arrays containing keys and values. This is useful when you have parallel arrays where each index corresponds to a key-value pair.
Problem Setup
Suppose we have two arrays:
const keys = [0, 4, 2, 3, 1]; const values = ["first", "second", "third", "fourth", "fifth"];
We need to create a Map where each key from the first array maps to the corresponding value from the second array at the same index.
Using a for Loop
The most straightforward approach is to iterate through both arrays and add each key-value pair to the Map:
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));
Map(5) {
0 => 'first',
4 => 'second',
2 => 'third',
3 => 'fourth',
1 => 'fifth'
}
Using Array.map() with Map Constructor
A more functional approach uses the Map constructor with an array of key-value pairs:
const keys = [0, 4, 2, 3, 1];
const values = ["first", "second", "third", "fourth", "fifth"];
const buildMapFunctional = (keys, values) => {
return new Map(keys.map((key, index) => [key, values[index]]));
};
console.log(buildMapFunctional(keys, values));
Map(5) {
0 => 'first',
4 => 'second',
2 => 'third',
3 => 'fourth',
1 => 'fifth'
}
Using forEach Method
Another approach using the forEach method for iteration:
const keys = [0, 4, 2, 3, 1];
const values = ["first", "second", "third", "fourth", "fifth"];
const buildMapForEach = (keys, values) => {
const map = new Map();
keys.forEach((key, index) => {
map.set(key, values[index]);
});
return map;
};
console.log(buildMapForEach(keys, values));
Map(5) {
0 => 'first',
4 => 'second',
2 => 'third',
3 => 'fourth',
1 => 'fifth'
}
Comparison of Methods
| Method | Readability | Performance | Best For |
|---|---|---|---|
| for loop | Good | Fastest | Large datasets |
| Map constructor | Excellent | Good | Functional programming |
| forEach | Very Good | Good | General purpose |
Conclusion
All three methods effectively create a Map from parallel arrays. The Map constructor approach is most concise, while the for loop offers the best performance for large datasets.
