Reputation: 39
I have a hash table of arrays, ie:
function (findPairs) {
var arrMaster = [];
var hash = {
a: [1,2,3,4,5],
b: [2,3,5,7,9],
c: [7,2,3,8],
d: [1,2]
}
return arrMaster
}
My goal is to return an array that shows all pairs of keys who have three instances of a common element in their value array. eg, in above example:
I sketched out code in JSFiddle. My main roadblock now is comparing a given value array to all other value arrays - I have code that compares any array to the immediate successive array. The code is getting quite complicated, with multiple nests, and frankly my head is spinning.
Upvotes: 0
Views: 118
Reputation: 1561
You could create an intermediate function to find the pairs like so:
function isPair(first, second) {
var values = {},
pairsFound = 0;
for (var i = 0; i < first.length; i++) {
var str = first[i];
values[str] = true;
}
for (var j = 0; j < second.length; j++) {
if (values[second[j]] === true) {
pairsFound++;
}
}
return pairsFound > 3;
}
Upvotes: 0
Reputation: 340045
Think in smaller code chunks, i.e. how could you count the number of common elements in a pair of arrays:
function countCommon(a, b) {
return a.reduce(function(p, c, e) {
return p + (b.indexOf(c) >= 0 ? 1 : 0);
}, 0);
}
Your problem is then reduced (no pun intended) to creating all possible pairs of the keys of hash
and evaluating the above function for each key's data:
function makePairs(hash) {
var result = [];
var keys = Object.keys(hash);
for (var i = 0, n = keys.length; i < n; ++i) {
for (var j = i + 1; j < n; ++j) {
result.push([keys[i], keys[j]]);
}
}
return result;
}
and then you just need the pairs that satisfy the criteria:
var result = makePairs(hash).filter(function(pair) {
return countCommon(hash[pair[0]], hash[pair[1]]) >= 3;
});
Hey presto, only one nested loop! Demo at http://jsfiddle.net/alnitak/kxdngy7n/
Upvotes: 1