0

So, the thing is I'm not really good at Javascript (I only know some C programming) & i want to implement a tree structure in which the node contains 2 arrays inside an array.

I could help you by giving structures in C:

struct IndexArray {
   void *DataArray;
   void *ChildsArray;
}

struct Node {
   struct IndexArray *ContainerArray;
}


In short words the node contains an array & each element of this array contains 2 sub arrays.

I searched for tree implementations in javascript & i found many examples but i couldn't find an implementation similar to this one.

5
  • Are you trying to create a function which accepts parameters and returns Array(Array(),Array())? Commented Feb 12, 2017 at 1:48
  • JavaScript is a weekly-typed language so you don't have to define a 'type' like you do in C. Almost everything in Javascript is an object. What would like this object to do or what are the behaviours of it? Commented Feb 12, 2017 at 1:50
  • I want to create the node for this tree ? How should it be declared in Javascript ? @guest271314 Commented Feb 12, 2017 at 1:51
  • @afr0ck var node = Array(Array(), Array()) or var node = [[],[]] Commented Feb 12, 2017 at 1:56
  • That object should contain 2 arrays inside one big array. something like this: var node = new node(); node.IndexArray[i] gives access to element i of node.IndexArray node.IndexArray[i].dataArray[j] gives access to element j of dataArray of element i of indexArray. & similarly node.indexArray[i].childArray[j] @guest271314 @xtu Commented Feb 12, 2017 at 1:57

1 Answer 1

1

You can create an Array in javascript using Array() constructor or array literal []

function _Node(a, b) {
  this.IndexArray = [[a], [b]];
}

var node = new _Node(1, 2);
var i = 1;
console.log(node.IndexArray[i]);

Alternatively

class _Node {
  constructor (a = 1, b = 2) {
    this.IndexArray = [[a], [b]];
  }
}

var node = new _Node(1);
var i = 1;
console.log(node.IndexArray[i]);

Sign up to request clarification or add additional context in comments.

5 Comments

How to access elements of the sub arrays [1] & [2] ? Let's say we want to access 4th element of sub array [1] ?
Note, arrays are 0-indexed. node.IndexArray[1][3] would get second array of node.IndexArray and fourth element of subarray.
That was very useful, can i use node.IndexArray.length ?
Yes, node.IndexArray is an instance of Array, which has .length property. Note the _ before Node, as Node is a DOM function.
OK. This should have solved the problem, thanks for helping.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.