Skip to content Skip to sidebar Skip to footer

How To Loop Through & Display Javascript Multidimensional Array

I have a testing search software and it stores the data in a multidimensional array. I can return the whole database but cannot return just one value. I'm trying to figure out how

Solution 1:

To return a value in a multidimensional array: array[n][m] is the mth element of the nth row. To do this for every element, use embedded for-loops:

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

Solution 2:

Using jQuery - but easily adaptable to pure JS:

var my_multi_dimensional_array = ["a", "b", "c", ["d", "e", "f"], "g", ["h", ["i"],
    ["j", "k"], "l", ["m", ["n", "o", [
        [
            ["p"], "q"]
    ]]]
]];

(function walkies(arr, path, callback, root) {
    $.each(arr, function (i, v) {
        //push index onto path stack
        path.push(i);
        var recurseable = ($.isArray(v) || $.isPlainObject(v)) ;
        var recurse = callback.call(v, !recurseable, v, path, i, root || arr) && recurseable;

        //call callback and continue recursing this node until callback returns false
        if ( recurse) {
            walkies(v, path, callback, root || arr);
        }

        //pop last index off path stack
        path.pop();
    });
}(my_multi_dimensional_array, [], function (isLeaf, node, path, index, root) {
    if( isLeaf ){
        console.log( "[" + path.join("],[") + "]=" + node );
    }
    return true;
}));

jsFiddle


Post a Comment for "How To Loop Through & Display Javascript Multidimensional Array"