繁体   English   中英

通过javascript中的兄弟姐妹链接对象

[英]Chaining objects by siblings in javascript

我有一个简单的问题,有一个对象,其中的元素具有其连接的数组。 仅对兄弟姐妹:

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

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

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

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

提前致谢!

这是我建议的解决方案,只需稍微修改一下调用函数的参数即可。 也许您也想将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/

如果您不想陷入循环并遍历所有兄弟姐妹,则可能需要像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.

希望这可以帮助 :)。

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
}

Ouput-测试用例

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM