Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

looping through arrays of arrays

I have an arrays of arrays (some thing like graph), How to iterate all arrays?

var parentArray = [
 [[1,2,3],[4,5,6],[7,8,9]],
 [[10,11,12],[13,14,15],[16,17,18]],
 [[19,20,21],[22,23,24],[26,27,28]]
];

Its just an example array, actual can contains any number of array and then arrays. How to print all those numbers? Its similar to html objects DOM

like image 343
coure2011 Avatar asked Aug 18 '11 11:08

coure2011


2 Answers

This recursive function should do the trick with any number of dimensions:

var printArray = function(arr) {
    if ( typeof(arr) == "object") {
        for (var i = 0; i < arr.length; i++) {
            printArray(arr[i]);
        }
    }
    else document.write(arr);
}

printArray(parentArray);
like image 194
Sascha Galley Avatar answered Oct 08 '22 14:10

Sascha Galley


For 2 dimenional Arrays:

for(var i = 0; i < parentArray.length; i++){
    for(var j = 0; j < parentArray[i].length; j++){

        console.log(parentArray[i][j]);
    }
}

For arrays with an unknown number of dimensions you have to use recursion:

function printArray(arr){
    for(var i = 0; i < arr.length; i++){
        if(arr[i] instanceof Array){
            printArray(arr[i]);
        }else{
            console.log(arr[i]);
        }
    }
}
like image 27
Van Coding Avatar answered Oct 08 '22 14:10

Van Coding