0

Please find the tree

var TreeModel = require('tree-model');
tree = new TreeModel();
rootMain = tree.parse(
    {id: 1,
    children: [
        {
            id: "11",
            children: [{id: "111"}]
        },
        {
            id: "12",
            children: [{id: "121"}, {id: "122"}]
        },
        {
            id: "13"
        }]
    },
    {id: 2,
    children: [
        {
            id: "21",
            children: [{id: "211"}]
        },
        {
            id: "22",
            children: [{id: "221"}, {id: "222"}]
        },
        {
            id: "23"
        }
    ]});
  1. Suppose I'm on node 2 I wanted to know its first sibling so it should return me 1.
  2. Second I'm on node 13 / 12 I wanted to know its first sibling then it should return 11.
  3. Second I'm on node 122 I wanted to know its first sibling then it should return 121.

Guide me how can I achieve this. I tried with walk and find method but no luck.

Mukesh S
  • 367
  • 5
  • 19

1 Answers1

0

First get a reference to the node you are, assume 122:

var node122 = rootMain.first(n => n.model.id === "122")

Then get the reference to the parent and get the first child:

var firstSiblingOfNode122 = node122.parent.children[0]
jnuno
  • 711
  • 5
  • 8