Rui Teixeira
Rui Teixeira

Reputation: 47

JS Multidimensional Array with No Fixed Size

In my program I have:

an array currentIndex that will look something like [1, 2, 2] a multidimensional array directions that looks like [1, [2, 0, [2, 3, -]] 1]

How can I loop through the first one in such a way that I can access directions[1][2][2] (turn the first array in the indexes of the second) ?

Upvotes: 1

Views: 128

Answers (3)

Claudio Santos
Claudio Santos

Reputation: 1317

To access directly one value you could use vector[1][2], but remember that the array index starts with 0.

But, if you want to walk through the vector you need a recursive function:

function printRecursiveArray(value, c){
  for(c=0; c<value.length; c++){

    if (typeof value[c] !=='object'){
      console.log(value[c]);     
    }else{
      printRecursiveArray(value[c],0);

    }

  }
}
var vector = [1,[1,2,3],2,3];
printRecursiveArray(vector,0);
console.log('vector[1][2]:' + vector[1][2]);// To access directly

So, your array could have any dimension, but you still print the elements.

Upvotes: 1

Emil Stolarsky
Emil Stolarsky

Reputation: 108

From what I understand you want to iterate through the first array where each value in the first array is the index you want to access in the multidimensional array. The following recursive function should work:

//index: Array of indexes 
//arr: The mutlidimensional array 
function accessMutliArr (index, arr) {
    if (index.length === 1)
        return arr [ index ];
    else {
        var currentIndex = index.splice(0, 1);
        return accessMutliArr (index , arr [ currentIndex ]);
    }
}

Upvotes: 1

StackSlave
StackSlave

Reputation: 10617

If you want to loop over a multidimensional Array then the process can look like:

for(var i in directions){
  for(var n in direction[i]){
    for(var q in directions[i][n]){
      var innerIncrement = q, innerValue = directions[i][n][q];
    }
  }
}

Take into account that a for in loop will automatically make your indexes Strings. The following is a fail proof way to do the same thing, with some other help:

for(var i=0,l=directions.length; i<l; i++){
  var d = directions[i];
  for(var n=0,c=d.length; n<c; n++){
    var d1 = d[n];
    for(var q=0,p=d1.length; q<p; q++){
      var innerIncrement = q, innerValue = d1[q];
    }
  }
}

When you do a loop like either of the above, imagine that each inner loop runs full circle, before the outer loop increases its increment, then it runs full circle again. You really have to know what your goal is to implement these loops.

Upvotes: 0

Related Questions