3

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

Manse
38.1k11 gold badges88 silver badges112 bronze badges
asked May 9, 2013 at 11:24
1
  • 2
    Do you know how to loop over a single array ? Commented May 9, 2013 at 11:32

2 Answers 2

3

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]]);
}
answered May 9, 2013 at 11:36
Sign up to request clarification or add additional context in comments.

1 Comment

Unfortunately, this solution only works for 3-dimensional arrays. However, I've found a way to loop through arrays with any number of dimensions (which may be more useful): stackoverflow.com/a/15854485/975097
1

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/

answered May 9, 2013 at 11:51

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.