How to useObject and for…in loop in Javascript
In this approach, we’ll first convert both maps into objects, merge them by iterating through the keys, and then convert the merged object back into a Map.
Syntax:
for (variable in object) {
// code block to be executed
}
Example:
function combineMaps(map1, map2) {
let obj = {};
// Convert map1 to object
for (let [key, value] of map1) {
obj[key] = value;
}
// Update or add values from map2
for (let [key, value] of map2) {
obj[key] = (obj[key] || 0) + value;
}
// Convert object back to map
let combinedMap = new Map();
for (let key in obj) {
combinedMap.set(key, obj[key]);
}
return combinedMap;
}
let map1 = new Map([['HTML', 1], ['CSS', 2]]);
let map2 = new Map([['JavaScript', 3], ['HTML', 4]]);
let result = combineMaps(map1, map2);
console.log(result);
Output
Map(3) { 'HTML' => 5, 'CSS' => 2, 'JavaScript' => 3 }
JavaScript Program to Combine Values of Two Maps having Same Key
In this article, we are going to learn about combining the values of two maps having the same keys in JavaScript, Combining values of two maps with the same key involves merging corresponding values from each map, creating a new map that retains unique keys while accumulating shared values.
There are different approaches to Combining the values of two maps having the same key in JavaScript. Let’s discuss each of them one by one.
Table of Content
- Approach 1: Using forEach
- Approach 2: Using a custom function
- Approach 3: Using Array.from and reduce
- Approach 4: Using Object and for…in loop
We will explore all the above methods along with their basic implementation with the help of examples.