Reputation: 31
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]
] .
Upvotes: 3
Views: 6476
Reputation: 27
u may try this:
First we compare the size
Then we loop through whether map2 key and val is the same as map1.
function equals(map1, map2) { if (map1.size !== map2.size) return false; for (let [key, val] of map1) { if (map2.get(key) !== val) return false; } return true; }
Upvotes: -2
Reputation: 123
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;
}
Upvotes: 1
Reputation: 171669
A simple way to compare the arrays is to stringify them and see if the sample one exists in the other string
let sample = {
'124': [9,9,9], // expect no match .. key exists but array differs
'125': [1, 2, 3], //expect match
'555':[8,8] // expect no match ... key doesn't exist
}
let data = {
'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]]
}
let res = Object.keys(sample).map(key => {
let msg = 'OK';
if(!data.hasOwnProperty(key)){
msg= 'No Match';
}else{
let arrayMatch = JSON.stringify(data[key]).indexOf(JSON.stringify(sample[key])) >-1;
msg = !arrayMatch ? 'No Match' : msg;
}
return key + ' : ' + msg;
});
console.log(res.join('\n'))
Upvotes: 0