Skip to content Skip to sidebar Skip to footer

Setting Up A Variable Length Two-dimensional Array

I have a string as follows : Panther^Pink,Green,Yellow|Dog^Hot,Top This string means I have 2 main blocks(separated by a '|') : 'Panther' and 'Dog' Under these two main blocks, I

Solution 1:

To me the most logical representation of your data:

Panther^Pink,Green,Yellow|Dog^Hot,Top

Is with a JavaScript object with a property for each category, each of which is an array with the subcategories:

vardata = {
   Panther : ["Pink", "Green", "Yellow"],
   Dog     : ["Hot", "Top"]
}

You would then access that by saying, e.g., data["Dog"][1] (gives "Top").

If that format is acceptable to you then you could parse it as follows:

function parseData(data) {
   var result = {},
       i,
       categories = data.split("|"),
       subcategories;

   for (i = 0; i < categories.length; i++) {
      subcategories = categories[i].split("^");
      result[subcategories[0]] = subcategories[1].split(",");
   }

   return result;
}

var str = "Panther^Pink,Green,Yellow|Dog^Hot,Top";
vardata = parseData(str);

Solution 2:

Assuming you're trying to parse your data into something like this:

var result = {
   Panther: ["Pink", "Green", "Yellow"],
   Dog: ["Hot", "Top"]
}

you can use string.split() to break up your string into subarrays:

var str = "Panther^Pink,Green,Yellow|Dog^Hot,Top";
var result = {}, temp;
var blocks = str.split("|");
for (var i = 0; i < blocks.length; i++) {
    temp = blocks[i].split("^");
    result[temp[0]] = temp[1].split(",");
}

Data can then be added to that data structure like this:

result["Cat"] = ["Cute", "Proud"];

Data can be read from that data structure like this:

var dogItems =result["Dog"];    // gives you an array ["Hot", "Top"]

Solution 3:

You can use something like:

functionparseInput(_input) {
  var output = [];
  var parts = _input.split('|');
  var part;
  for(var i=0; i<parts.length; i++) {
    part = parts[i].split('^');
    output[part[0]] = part[1].split(',');
  }
  return output; 
}

Calling parseInput('Panther^Pink,Green,Yellow|Dog^Hot,Top'); will return:

output [
 "Panther" => [ "Pink", "Green", "Yellow" ],
 "Dog" => [ "Hot", "Top" ]
]

To add another item to the list, you can use:

output["Cat"] = ["Cute", "Proud"];

Post a Comment for "Setting Up A Variable Length Two-dimensional Array"