JavaScript Program to Combine Values of Two Maps having Same Key
Last Updated :
03 Jun, 2024
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.
We will explore all the above methods along with their basic implementation with the help of examples.
Approach 1: Using forEach
In this approach, we Iterate through one map using forEach, set initial values in a new map, and then update values by adding corresponding values from the second map if the keys match.
Syntax:
array.forEach( callback(element, index, arr), thisValue )
Example: In this example, we are merging values from map1 and map2, where existing keys in the resulting map are updated by adding corresponding map2 values, and new keys are added with their values.
JavaScript
const map1 = new Map([['India', 1], ['Usa', 2]]);
const map2 = new Map([['India', 3], ['Russia', 4]]);
const result = new Map([...map1]);
map2.forEach((value, key) => {
if (result.has(key)) {
result.set(key, result.get(key) + value);
} else {
result.set(key, value);
}
});
console.log(result);
OutputMap(3) { 'India' => 4, 'Usa' => 2, 'Russia' => 4 }
In this approach, we are using custom function, combineMaps, merges two maps by iterating through the second map's entries, updating or adding values in the first map based on matching keys.
Syntax:
function combineMaps(map1, map2) {
// Code
return combinedMap;
}
Example: In this example we are using the above-explained approach.
JavaScript
function combineMaps(map1, map2) {
let combinedMap = new Map([...map1]);
map2.forEach((value, key) => {
if (combinedMap.has(key)) {
combinedMap.set(key, combinedMap.get(key) + value);
} else {
combinedMap.set(key, value);
}
});
return combinedMap;
}
let map1 = new Map([['JavaScript', 1], ['HTML', 2]]);
let map2 = new Map([['JavaScript', 2], ['CSS', 4]]);
let result = combineMaps(map1, map2);
console.log(result);
OutputMap(3) { 'JavaScript' => 3, 'HTML' => 2, 'CSS' => 4 }
In this approach, Combines values of two maps by converting entries to arrays, concatenating them, then using reduce to update or set values based on matching keys.
Syntax:
Array.from(object, mapFunction, thisValue) // Array.form
array.reduce( function(total, currentValue, currentIndex, arr), initialValue )
Example: In this example we are using the above-explained approach.
JavaScript
let map1 = new Map([['HTML', 1], ['CSS', 2]]);
let map2 = new Map([['JavaScript', 3], ['HTML', 4]]);
let combinedMap = new Map(
Array.from(map1)
.concat(Array.from(map2))
.reduce((ele, [key, value]) => {
ele.set(key, (ele.get(key) || 0) + value);
return ele;
}, new Map())
);
console.log(combinedMap);
OutputMap(3) { 'HTML' => 5, 'CSS' => 2, 'JavaScript' => 3 }
Approach 4: Using Object and for...in loop
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:
JavaScript
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);
OutputMap(3) { 'HTML' => 5, 'CSS' => 2, 'JavaScript' => 3 }
Similar Reads
JavaScript Program to Split Map Keys and Values into Separate Arrays
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 in
5 min read
How to Add a key/value Pair to Map in JavaScript ?
This article will demonstrate how we can add a key-value pair in the JavaScript map. JavaScript Map is a collection of key-value pairs in the same sequence they are inserted. These key values can be of primitive type or the JavaScript object. All methods to add key-value pairs to the JavaScript Map:
3 min read
How to convert a Set to Map in JavaScript?
A Set is a collection of unique values. It stores only the data in the form of values while a Map can store the data in the form of key-value pairs. These are the different ways of converting a Set to a Map in JavaScript: Table of Content Using the Array.from() methodUsing the Spread Operator with m
3 min read
JavaScript Program to Merge Two Sets
Given two sets, our task is to Merge Two Sets into a new set so that unique elements will be present in the new set from both sets. Example:Input:set1 = ([1, 2, 3, 4])set2 = ([3, 4, 5, 6])Output:Set(5) { 1, 2, 3,4, 5, 6} Explanation:The unique elements present in set are : 1, 2, 3, 4, 5, 6Below are
3 min read
How to convert a Map into a Set in JavaScript?
Map and Set in JavaScript are special kind of data structures that holds only the unique data. There will be no duplicate data stored in them. Maps store data in the form of key-value pairs, while the Sets store in the form of values only. In some scenarios, you need to convert a Map into a Set, the
4 min read
JavaScript Map keys() Method
The Map.keys() method is used to extract the keys from a given map object and return the iterator object of keys. The keys are returned in the order they were inserted.Syntax:Map.keys()Parameters:This method does not accept any parameters.Return Value:This returns the iterator object that contains k
3 min read
JavaScript Map size Property
Map is a collection of elements where each element is stored as a Key, value pair. The Map.size property returns the number of key, and value pairs stored in a map.SyntaxmapName.sizeReturn ValueAn integer representing the number of key, value pairs stored in a map.The below examples illustrate the M
1 min read
JavaScript Map entries() Method
JavaScript Map.entries() method is used for returning an iterator object which contains all the [key, value] pairs of each element of the map. It returns the [key, value] pairs of all the elements of a map in the order of their insertion. The Map.entries() method does not require any argument to be
4 min read
JavaScript Map get() Method
The Map.get() method in JavaScript is a convenient way to retrieve the value associated with a specific key in a Map object. A Map in JavaScript allows you to store key-value pairs where keys can be of any data type, making it more useful compared to objects, which only allow strings and symbols as
3 min read
JavaScript Map Reference
JavaScript Map is a collection of elements where each element is stored as a key, value pair. Map objects can hold both objects and primitive values as either key or value. When we iterate over the map object it returns the key, and value pair in the same order as inserted.You can create a JavaScrip
3 min read