How to useArray.from and reduce in Javascript
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.
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);
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.
Contact Us