2

I am writing a function which is indexing a 1D Array in more dimension. The user can choose the depth of the index.

eg.

var store = ["Alaska", "Alabama", "North Korea", "South Korea"];

the user can choose for example depth 1. It means it will be index by the first char of the string

index["a"] = ["Alaska", "Alabama"];
index["n"] = ["North Korea"];

if the user chooses depth = 2 than it will be 2D Array with index the two beginning chars

index["a"]["l"] = ["Alaska", "Alabama"];

etc.

How do I accomplish a function which can populate variable Dimension arrays in JavaScript?

var indexthis = function(store,depth)
{
  if(depth == "undefined")
  {depth =1;}
//any Suggestions to go on?
};

Greetings

5
  • 7
    How much are you going to pay me to write this for you? Commented Jul 9, 2014 at 13:01
  • What is such an index used for, i.e. what problem are you trying to solve? Is there a reason against simply searching the array? Commented Jul 9, 2014 at 13:04
  • 3
    This question appears to be off-topic because you are asking us to do the work for you Commented Jul 9, 2014 at 13:04
  • I was thinking about starting with the last Array var temp[store[i][depth-1]].push(store[i]). And then I need to push temp into another Var temp2. the index is used to fasten looking for special strings inside an Array Commented Jul 9, 2014 at 13:05
  • Loop through the array. if (first character does not have an array) create array. If second character does not have an array, create an array. Push the word to the array. Commented Jul 9, 2014 at 13:13

2 Answers 2

1

This function:

function indexWord(index, word, letters) {
    var letter;
    if (!letters) letters = word.split("");
    while (letters.length) {
        letter = letters.shift().toLowerCase();
        if (!(letter in index)) index[letter] = {_items: []};
        index[letter]._items.push(word);
        indexWord(index[letter], word, letters);
    }
}

called like this:

var store = ["Alaska", "Alabama", "North Korea", "South Korea"],
    index = {}, i;

for (i = 0; i < store.length; i++) {
    indexWord(index, store[i]);
}

gives you the following index:

{
  a: {
    _items: ["Alaska", "Alabama"],
    l: {
      _items: ["Alaska", "Alabama"],
      a: {
        _items: ["Alaska", "Alabama"],
        s: {
          _items: ["Alaska"],
          k: {
            _items: ["Alaska"],
            a: {
              _items: ["Alaska"]
            }
          }
        },
        b: {
          _items: ["Alabama"],
          a: {
            _items: ["Alabama"],
            m: {
              _items: ["Alabama"],
              a: {
                _items: ["Alabama"]
              }
            }
          }
        }
      }
    }
  },
  n: {
    _items: ["North Korea"],
    o: {
      _items: ["North Korea"],
      r: {
        _items: ["North Korea"],
        t: {
          _items: ["North Korea"],
          h: {
            _items: ["North Korea"],
            " ": {
              _items: ["North Korea"],
              k: {
                _items: ["North Korea"],
                o: {
                  _items: ["North Korea"],
                  r: {
                    _items: ["North Korea"],
                    e: {
                      _items: ["North Korea"],
                      a: {
                        _items: ["North Korea"]
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  },
  s: {
    _items: ["South Korea"],
    o: {
      _items: ["South Korea"],
      u: {
        _items: ["South Korea"],
        t: {
          _items: ["South Korea"],
          h: {
            _items: ["South Korea"],
            " ": {
              _items: ["South Korea"],
              k: {
                _items: ["South Korea"],
                o: {
                  _items: ["South Korea"],
                  r: {
                    _items: ["South Korea"],
                    e: {
                      _items: ["South Korea"],
                      a: {
                        _items: ["South Korea"]
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}

where either index["a"]["l"]._items or index.a.l._items can be used to access ["Alaska", "Alabama"].

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

5 Comments

This seems more useful despite departing a bit from the OPs requirements.
The OP's requirements cannot be met anyway. Unless of course you use nested arrays instead of objects and define one-letter properties on those arrays themselves. This is an unclean approach. And does not translate to JSON.
Well, the OP never asked for results at the interim keys. Don't get me wrong, I like what you've done (+1 btw). It's just not what was asked for... and the fact that the OP selected an answer (fiddle) which doesn't provide results on the interim keys sort of supports my point.
Ah, I see what you mean. Well, yes, I thought I build a full index right-away.
I'm not sure if such a colossal waste of memory really serves any useful purpose, though. I mean, look what it does with a four-word input, think what it does with a 4000-word input. I'm pretty sure there is a better algorithm out there to do this kind of thing. Since the OP does not really tell what he wants to achieve in the first place, this is nothing more than an academic example for basic recursion.
0

This seems to meet your requirements:

function createIndex(store, depth) {
    var index = {}; 
    depth = depth || 1;

    // loop over each item in the store
    store.forEach(function (item) {
        var lower = item.toLowerCase(),
            current = index,
            char;

        // loop over the characters, building the store structure
        for (i = 0; i < depth; i++) {
            char = lower.substr(i, 1); 

            // add the key, if it doesn't exist
            if (!current[char]) {
                current[char] = (i == (depth - 1) ? [] : {});
            }   

            // update the object reference
            current = current[char];
        }   

        // now add the item
        current.push(item);
    }); 

    return index;
}

Comments

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.