1

apparently I can't understand how JS's logic works when parsing data from multidimensional arrays.

let's say we have a 3D array as this:

 var data = new Array(("1","2",("7","8","9")),("3","4",("10","11","12")),("5","6",("13","14","15")));

and I have a simple HTML structure to start with like a single div with id=parentdiv

and i want to append it in the DOM in order to look like every dimension is in a different div but still child to the div of the previous dimention ending up in something like: childdiv1:( 1 2 grandchilddiv1.1: 7 grandchilddiv1.2: 8 grandchilddiv1.3: 9) childdiv2:( 3 4 grandchilddiv2.1: 10 grandchilddiv2.2: 11 grandchilddiv2.3: 12) childdiv3:( 5 6 grandchilddiv3.1: 13 grandchilddiv3.2: 14 grandchilddiv3.3: 15) ending up printing a simple 1 2 7 8 9 3 4 10 11 12 5 6 13 14 15

setting up a fiddle to check how loops work.. http://jsfiddle.net/M_Elf/68zfgdaq/1/ Using $each instead of for ofcourse doesn't change anything what I noticed is that each loop is acting like independently from its parent loops... Never seen examples parsing data from more than 2 dimensions and a loop inside a loop doesn't seem to work as I predicted... Any suggestions?


solved with recursion way of thinking

1 Answer 1

1

I don't think you're using the Array() constructor properly. It's a bit unconventional to use that constructor rather than just var arr = [1, 2, 3];

The problem is that the Array() constructor expects each argument to be a single value or object; instead you're trying to feed it multidimensional arrays, but you aren't constructing those inner arrays properly! It should probably look something like this:

var data = new Array(new Array(1, 2, 3), new Array(4, 5, 6), new Array(7, 8, 9));

An easier and more intuitive way to do it would be to just declare the array like this:

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

It makes it easier to see how the arrays nest and what the multidimensional structure is.

Sign up to request clarification or add additional context in comments.

5 Comments

by transforming the array into a form like` "var data = [[1, 2, [7, 8, 9]], [3, 4, [10, 11, 12]], [5, 6, [13, 14, 15]]];" ` then I guess the syntax should also change? JQuery says there are "parameter is not of type 'Node'" errors
This is a classic recursion problem. Take a gander at this fiddle: jsfiddle.net/belross/h54u2w58
recursion! exactly what i needed!
what if i wanted to put elements 7 8 9, 10 11 12 and 13 14 15 in 3 separate lists? inside a parent div?
@CookieMonster I'm not sure what you mean, but if you restructure the array you can achieve any nested order of elements that you want.

Your Answer

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.