Reputation: 1149
I have two hashmaps, hashmap1 and hashmap2. Each hashmap has multiple keys with multiple values for each key.
var hashmap1 = {
a:[
'aaa',
'bbb'
]
b:[
'ccc',
'ddd'
]
};
var hashmap2 = {
a:[
'aaa',
'bbb',
'ccc',
]
b:[
'ddd',
'eee',
'fff'
]
};
In the above example, I want to check if all of values for each key within hashmap1 exist within values of hashmap2.
So in the above example all values within hashmap1 are present within the values of hashmap2. If this is the case maybe to mark a variable as true else mark it as false.
Thanks for the help
Upvotes: 0
Views: 202
Reputation: 872
I just wrote a similar compare function. It uses jquery, I hope its not a problem.
/**
* Checks if an object or array is a subset of another object or array.
* Also works with scalar types.
*
* @requires jQuery
* @param {mixed} partial
* @param {mixed} whole
* @param {boolean} strict_arrays In arrays, compare with a[i] === b[i] instead of inArray(a[i], b). Default false.
* @returns {boolean} 'partial' is a subset of 'whole'
*/
function is_subset(partial, whole, strict_arrays) {
if (partial instanceof Array) {
if (!(whole instanceof Array)) return false;
var matches = true;
$.each(partial, function(i, value){
if ((!strict_arrays && $.inArray(value, whole) < 0) || (strict_arrays && value !== whole[i])) {
matches = false;
return false;
}
});
return matches;
} else if (typeof partial === 'object' && partial !== null) {
if (!(typeof whole === 'object')) return false;
var matches = true;
$.each(partial, function(prop, value) {
if (!is_subset(value, whole[prop])) {
matches = false;
return false;
}
});
return matches;
} else {
return partial === whole;
}
}
Usage with your example: is_subset(hashmap1, hashmap2)
Upvotes: 1