Javascript - Add two hash maps

java merge two maps with same key
java hashmap merge function
java merge maps with duplicate keys
merge two maps java 8
java 8 merge maps with duplicate keys
merge two maps javascript
adding the values of two maps with same key
kotlin merge maps

I have two hash maps as follows



output expected

an easy solution is to loop through each map and add values to new map, but is there a more efficient way ?

You can use Object.entries to convert the object into an array. Summarize the array using reduce

let m1 = {};
m1['a'] = {};
m1['b'] = {};
m1['a']['x'] = 5;
m1['b']['x'] = 6;
m1['a']['y'] = 4;
m1['b']['y'] = 6;

let m2 = {};
m2['a'] = {};
m2['b'] = {};
m2['a']['x'] = 8;
m2['b']['x'] = 7;
m2['a']['y'] = 6;
m2['b']['y'] = 4;
m2['a']['z'] = "name";

let m3 = Object.entries(m1).reduce((c, [i, v]) => {
  let addOnly = ['x', 'y'];
  c[i] = c[i] || {};

  //Loop thru m1
  Object.entries(v).reduce((x, [k, o]) => Object.assign(x, {[k]: o}), c[i]);

  //Loop thru m2 
  Object.entries(m2[i]).reduce((x, [k, o]) => {

    if (addOnly.includes(k)) {
      x[k] = x[k] || 0;
      x[k] += o;
    } else {
      x[k] = x[k] || o;

    return x;
  }, c[i]);

  return c;
}, {})


How can I combine two HashMap objects containing the same types , Note that if multiple maps have the same key, the value of the merged map will be that you can then require() into node.js and use in place of the built-in Set. I currently have a need to temporarily swap out values in a JavaScript string, and therefore I will need to have a two-way map/hash thing. For example, let's say I want to change \* to __asterisk__ (this is just an example, it's not what I'm actually trying to do).

You could check if the value is an object and create a new object with a recursive call of the merge function. Otherwise return the result of the addition.

function merge(o1, o2) {
    return o1 && typeof o1 === 'object'
        ? Object.assign(...Object.keys(o1).map(k => ({ [k]: merge(o1[k], o2[k]) })))
        : o1 + o2;

var m1 = { a: { x: 5, y: 4 }, b: { x: 6, y: 6 } },
    m2 = { a: { x: 8, y: 6 }, b: { x: 7, y: 4 } };

console.log(merge(m1, m2));

Simplest way to merge ES6 Maps/Sets?, In this quick tutorial, we'll demonstrate how to merge two maps using the Java 8 capabilities. private static Map<String, Employee> map1 = new HashMap<>(); First, we need to combine our Map instances into one Stream. Java HashMap. You learned from the previous chapter, that Arrays store items as an ordered collection, and you have to access them with an index number (int type).A HashMap however, store items in "key/value" pairs, and you can access them by an index of another type (e.g. a String).

As long as we're over-engineering this why not calculate the values when you need them rather than in a loop ;)

let m1 = { a: { x: 5, y: 4 }, b: { x: 6, y: 6 } };
let m2 = { a: { x: 8, y: 6 }, b: { x: 7, y: 4 } };

let m3 = new Proxy({}, {
    get: function(target, ab) {
            return new Proxy({}, {
                get: function(target,xy) {
                    return m1[ab][xy] + m2[ab][xy]

Merging Two Maps with Java 8, The merge(Key, Value, BiFunctional) method of HashMap class is used to combine multiple mapped values for a key using the given mapping function. Bucket  Map.prototype.entries() Returns a new Iterator object that contains an array of [key, value] for each element in the Map object in insertion order. Map.prototype.forEach(callbackFn[, thisArg]) Calls callbackFn once for each key-value pair present in the Map object, in insertion order.

HashMap merge(key, value, BiFunction) method in Java with , Map<String, Integer> numbers = new HashMap<>(); numbers.put("One", "One" -> 1 "Two" -> 2 "Three" -> 4 //old value 3 was overwritten by new value 4  There you have it, 5 ways to use a JavaScript hashmap. If you have examples of other uses, or if you’ve implemented a JS hashmap yourself that you’d like to share, please feel free to drop the link to your code in the comments below. And finally, I referenced the following articles to help me with writing this one. Many thanks to the authors!

Java Language, Well organized and easy to understand Web building tutorials with lots of examples of how to use HTML, CSS, JavaScript, SQL, PHP, Python, Bootstrap, Java  The map() method creates a new array with the results of calling a function for every array element. The map() method calls the provided function once for each element in an array, in order. Note: map() does not execute the function for array elements without values. Note: this method does not change the original array.

Java HashMap, put(Object KEY, String VALUE) – This method stores the specified value and associates it with the specified key in this map. Java Hashmap  Find local businesses, view maps and get driving directions in Google Maps. When you have eliminated the JavaScript , whatever remains must be an empty page. Enable JavaScript to see Google Maps.

  • No. You have to look at every single value anyway, you won't get better than linear complexity.
  • It's such a simple loop. Don't over think it
  • That being said there are lots of different ways to construct the loop, all with same complexity. Good exercise to try a bunch of them
  • Are you sure you want a new object and not a function that returns the sum?
  • great answer, what if i want to add a "id" so it shouldn't be added and should be copied only, any way ?
  • Thanks, can you give an example on how you want to add your id?
  • for example if m2['a']['z']="name"; so m3['a']['z'] = "name" and not name+name, also m2[a][x] is undefined but m1['a']['x'] = value
  • @JenuRudan Please check updated code. I also added an array addOnly to list all properties are needed to add. Please check