在javascript中由兄弟姐妹链接对象

时间:2014-06-25 10:21:40

标签: javascript chaining lodash

我有一个简单的问题,有一个对象,哪些元素有一个连接数组。只对兄弟姐妹:

var obj = {
    1: [2],
    2: [1,3],
    3: [2,4],
    4: [3],

    5: [6],
    6: [5]
}

有两个连接,前4个连接,5和6.也连接。我会得到一个列表取决于所选元素,关于谁彼此连接。因此,如果我选择giveMeTheListOfSiblingIn(3),我想获得此列表:[1,2,3,4]

这并不难,因为我无法得到解决方案,总是避免无限循环。这是我在JSFiddle中的尝试,我使用了Lo-Dash框架,但你不必这样做。

提前致谢!

3 个答案:

答案 0 :(得分:1)

这是我建议的解决方案,只需稍微修改一下呼叫功能的参数即可。 也许你想发送obj作为一个参数。

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);

http://jsfiddle.net/9L5s6/1/

答案 1 :(得分:0)

如果你不想陷入困境并经历所有兄弟姐妹,你可能希望在某种tree处看到这一点,first visited节点是root。在这种情况下,您将使用recursive algorithm来遍历树。但是,您需要保存访问过的节点,以便不再访问它们。

实施例: 假设您先访问3节点。

3 has two connections, visit 2.
2 -> visit 1.
1 points to 2, but 2 is visited so return.
2 (because 2 points to 1) also points to 3, but 3 is visited so return.
3 also points to 4, visit 4.
4 points to 3, 3 is visited so return.
3 no more connections and also a root node so tree walking is complete.

希望这会有所帮助:)。

答案 2 :(得分:0)

var obj = {
    1: [2],
    2: [1,3],
    3: [2,4],
    4: [3],

    5: [6],
    6: [5]
}

//initiallly all siblings will be an empty string
var giveMeTheListOfSiblingIn = function(index, allSiblings) {
    //get imidiate or directly connected siblings
    var _mySiblings = obj[index];
    var me = index
    for(var i=0;i<_mySiblings.length;i++) {
        //if sibling is already added, don't add it again
        //ignore already found sibling and sibling of its sibling as its
        //siblings are already capture. See  push line below
        if(allSiblings.indexOf(_mySiblings[i]) == -1 && _mySiblings[i] != me) {
            //push currently found sibling
            allSiblings.push(_mySiblings[i])
            //get siblings of currently found sibling and pass all the siblings found yet
            //so that it will not search again for the same sibling
            allSiblings = giveMeTheListOfSiblingIn(_mySiblings[i], allSiblings)
        }
    }
    return allSiblings
}

输出 - 测试用例

giveMeTheListOfSiblingIn(2, [])
//output [1, 2, 3, 4]

giveMeTheListOfSiblingIn(6, [])
//output [5, 6]