Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript For loop in multidimensional javascript array

Can anyone give me a sample/example of JavaScript with a multidimensional array of inputs? Hope you could help because I'm still new to the JavaScript.

Like this:

 var cubes =   [[1, 2, 3],[4, 5, 6],[7, 8, 9]];

output : [1,4,7],
         [1,4,8],
         [1,4,9],
         [1,5,7],
         [1,5,8],
         [1,5,9],
         [1,6,7],
         [1,6,8],
         [1,6,8],
        ......... 
        .........
         [3,6,7],
         [3,6,8],
         [3,6,9]

Thanks

like image 500
Kim Ki Heung Avatar asked Apr 13 '26 19:04

Kim Ki Heung


2 Answers

This code should work:

var cubes = [[1, 2, 3],[4, 5, 6],[7, 8, 9]];

for(var i=0; i<cubes[0].length; ++i)
for(var j=0; j<cubes[1].length; ++j)
for(var k=0; k<cubes[2].length; ++k) {
    alert([cubes[0][i],cubes[1][j],cubes[2][k]]);
}
like image 169
Jan Turoň Avatar answered Apr 16 '26 07:04

Jan Turoň


This works for the given array, but means if you have more than three inner arrays, or more array dimensions then you would have to manually edit the javascript.

$(document).ready(function(){
    var cubes =   [[1, 2, 3],[4, 5, 6],[7, 8, 9]];
    var output = "";

    for(var a = 0; a < cubes[0].length; a++)
    for(var b = 0; b < cubes[1].length; b++)
    for(var c = 0; c < cubes[2].length; c++) {
        output = output + [cubes[0][a],cubes[1][b],cubes[2][c]] + ",<br />";
    }

    $('#output').html(output);
});

Working example: http://jsfiddle.net/HtSkd/

like image 41
Maloric Avatar answered Apr 16 '26 07:04

Maloric