Reputation: 2646
I'm having a little trouble with using javascript to split an array into a multi array. For instance, I have this array:
[0] => object
[0] => object
[0] => The Letter P
[1] => 5.5
[1] => object
[0] => 5
[1] => 1.1
[2] => 5
[3] => 1
[4] => 1
[2] => object
[0] => 5
[1] => 1.1.1
[2] => 1.1.1
[3] => 1.1.1
[4] => 3
What I would like to do is split up the periods, and create an even deeper array like this:
[0] => object
[0] => object
[0] => The Letter P
[1] => object
[0] => 5
[1] => 5
[1] => object
[0] => 5
[1] => object
[0] => 1
[1] => 1
[2] => 5
[3] => 1
[4] => 1
[2] => object
[0] => 5
[1] => object
[0] => 1
[1] => 1
[2] => 1
[2] => object
[0] => 1
[1] => 1
[2] => 1
[3] => object
[0] => 1
[1] => 1
[2] => 1
[4] => 3
I have tried just about everything that I can think of and I can't seem to find a code that works :( Please help me :(
Upvotes: 1
Views: 234
Reputation: 2646
thanks for all your replies but I managed to figure it out on my own. It's amazing what happens when you take a break from programming and let your mind go at ease. Anyways, knowing that I have three lays to start within my array, I was able to write the following code:
for(a = 0; a < array.length; a++){
for(var b = 0; b < array[a].length; b++){
for(var c = 0; c < array[a][b].length; c++){
if(array[a][b][c].indexOf(".") > 0){
array[a][b][c] = array[a][b][c].split(".");
}
}
}
}
At first I tried using while loops, but that required a lot more code and was a lot more confusing. Then I started using the for loop which works a lot better for this type of system. Thanks again for your replies and I hope this helps anyone else who tries to do the same thing.
Upvotes: 0
Reputation: 5197
Would this help?
var toString = Object.prototype.toString;
function parseArray(obj) {
var i, l;
if (toString.call(obj) === "[object Number]") {
obj += "";
}
if (toString.call(obj) === "[object String]" && obj.indexOf(".") !== -1) {
obj = obj.split(".");
}
if (toString.call(obj) === "[object Array]") {
for (i = 0, l = obj.length; i < l; i++) {
obj[i] = parseArray(obj[i]);
}
}
return obj;
}
Upvotes: 0
Reputation: 21830
This should work
function dotsToArr(arr) {
for(var x = 0; x < arr.length; x++) {
if(typeof(arr[x]) != "object") {
var parts = (arr[x]+"").split(".");
if(parts.length > 1) {
arr[x] = parts;
}
continue;
}
dotsToArr(arr[x]);
}
}
JS Fiddle here: http://jsfiddle.net/gER22/
Upvotes: 2
Reputation: 3281
It's not a complete solution, but I use this function to accomplish something like you're describing.
function parseStringToArray(inputString){
var parts = inputString.split(".");
var arr = [];
while (parts.length){
arr.push(parts.shift());
}
return arr;
}
function parseArray(inputArray){
var arrayLength = inputArray.length;
for (var i = 0; i < arrayLength; i++){
if (inputArray[i].indexOf('.'){
inputArray[i] = parseStringToArray(inputArray[i]);
}
}
}
Upvotes: 0