I have a simple problem, there is an object, which elements have an array of their connections. Only to the siblings:
var obj = {
1: [2],
2: [1,3],
3: [2,4],
4: [3],
5: [6],
6: [5]
}
There is two connections, the first 4 is connected to each other, and the 5. and 6. too. I would get a list depend on a selected element, about who is connected to each other. So if I select the giveMeTheListOfSiblingIn(3)
, i would like to get this list: [1,2,3,4]
.
It's not to difficult, by I can't get the solution, always avoid infinite loop. Here is my trying in JSFiddle, I used the Lo-Dash framework, but you do not have to.
Thanks in advance!
Here's my suggested solution, with a little modification of the call function's parameters. Maybe you would like to send obj as a param too.
var obj = {
1: [2],
2: [1,3],
3: [2,4],
4: [3],
5: [6],
6: [5]
}
list = [];
function call(id) {
if (list.indexOf(id) == -1) {
list.push(id);
obj[id].forEach(call)
}
return list;
}
var result = call(6);
console.log(result);