Search code examples
javascriptmultidimensional-arraytrie

Javascript: possible to dynamically create a multidimensional array?


I'm playing around with multidimensional arrays in Javascript. Basically I'm trying to put letters of a string into some kind of Trie (actually a Radix Tree), using a multi-dimensional array.

  var data= [];
  var word="test";

  if (l=word[0]) {
      if (!data[l]) {
          data[l] = [];
      }
  }
  if (l=word[1]) {
      if (!data[word[0]][l]) {
          data[word[0]][l] = [];
      }
  }
  if (l=word[2]) {
      if (!data[word[0]][word[1]][l]) {
          data[word[0]][word[1]][l] = [];
      }
  }
  if (l=word[3]) {
      if (!data[word[0]][word[1]][word[2]][l]) {
          data[word[0]][word[1]][word[2]][l] = [];
      }
  }

  console.log(data);

See fiddle: http://jsfiddle.net/TN28c/

I was wondering if this could be automated (without using eval()) to handle any-length words. I know Javascript doesn't have pointers/references, which is what I would probably use in PHP, but is there maybe another way?

I'm not looking for a trie-library, I already found some of these, but I was just wondering if the above is even possible to do dynamically in Javascript.


Solution

  • var word= 'tree';
    var data = [];
    var obj = data;
    for (var i = 0; i < word.length; i++) {
        if (!obj[word[i]]) {
            obj[word[i]] = []
        }
        obj = obj[word[i]];
    }
    console.log(data);