Given an table of links of the form:
const links = [
['a', 'b'],
['c', 'd'],
['e', 'f'],
['b', 'x'],
['x', 'z']
];
where the first column is unique i.e. links[0...length][0]
are all unique.
I would like to find all connections greater than 1. In the example above, the output should be
[["a", "b"], ["b", "x"], ["x", "z"]]
Here is my attempt which is based on a similar question for java
const links = [
['a', 'b'],
['c', 'd'],
['e', 'f'],
['b', 'x'],
['x', 'z']
];
connections = [];
const map = new Map()
const recurse = (value, key) => {
if (map.has(value)) {
if (key !== undefined) {
connections.push([key, map.get(key)]);
}
connections.push([value, map.get(value)])
recurse(map.get(value))
}
}
const findConnectionsWithMap = arr => {
arr.forEach(value => map.set(value[0], value[1]))
const keySet = map.keys();
//console.log(keySet);
while (key = keySet.next().value) {
recurse(map.get(key), key);
}
console.log(connections);
}
findConnectionsWithMap(links);
Current output is
[["a", "b"], ["b", "x"], ["x", "z"], ["b", "x"], ["x", "z"]]
I am not sure why the output is having duplicates but I am guessing it has to do with the recursion point.
Why is this happening? and is this the best approach for a large record set?