1

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) ?

1
  • You'll have to be more specific. I see where the - is, but don't know what your getting at. If you want to loop through directions[1][2] you can assign it to a variable and loop over it, since it is an Array. Commented Oct 25, 2013 at 0:00

3 Answers 3

1

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.

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

Comments

1

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 ]);
    }
}

Comments

0

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.

Comments

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.