Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare two hashmaps in javascript

Tags:

javascript

I try to find a solution to compare two hashmaps in javascript but I have a difficulty.

This is my situation, I have a hashmap composed of a key + value in form of an array.

Example : 125 : [1 , 2 , 3]

And then I take this data and I compare it with another hashmap with this kind.

Example :

123 : [[1 , 1 , 1][2 , 8.7 , 10]]
124 : [[0 , 0, 5.4][3 , 4 , 5][7, 9.1 , 6]
125 : [[1 , 2 , 3][0.4 , 4 , 8]]

The second hashmap is similar to the first , but its value could contain an array of N arrays. The goal : To parse the second hashmap with my first hashmap and firstly find if the keys are similar, then if once it finds the value of the first in an array of the second it must return "OK"

For example in this case : it will return "OK" because we can notice that the key 125 and her value in the first hashmap are included in 125 : [[1 , 2 , 3][0.4 , 4 , 8]]

I should not only test on the values ​​but also on the keys

Here is another example :

Notice that the first hashmap always have 1 data (key+value) 1 key + 1 array of 1 dimension

1st hashmap : var hashmap1 = { 124 : [ 1,1,1] }

2nd hashmap :

    var hashmap2 = { 
        123 : [0,0,0],
        124 : [[ 0,1,1][0,0,1][1,1,1]]
        125 : [9 , 8 , 7]
    }

Result : "OK" , because 124 : [1,1,1] is found in 124 : [[ 0,1,1][0,0,1][1,1,1]] .

like image 605
B Benkaddour Avatar asked Sep 17 '26 17:09

B Benkaddour


1 Answers

const compareHashMap = (obj1, obj2) => {
  const keys1 = Object.keys(obj1), keys2 = Object.keys(obj2);
  let match = true;
  if(keys1.length !== keys2.length) return false;
  for(const key of keys1) { 
      if(obj1[key] !== obj2[key]) {
          match = false; 
            break; 
      }
  }
  return match;
}
like image 199
Ellie Maynard Avatar answered Sep 19 '26 06:09

Ellie Maynard



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!