Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free.

I have the following multidimensional array setup:

array[key1][key2]["value1"] = "test";
array[key1][key2]["value2"] = "test2";

I know to iterate in the first level you use:

for(key in  array)
{

}

How would I iterate through the second level? I was trying this without any success

for(key in array)
{
    for(key2 in array[key])
    {

    }
}

Also, does anyone know how I can sort by the second key? I hope I'm not overcomplicating this

share|improve this question
    
If you appreciate an answer, don't forget to "accept" the best one by clicking the checkmark to the left of the answer, underneath the voting arrows. This will also award you some reputation points! If a better answer comes along later, you can switch to that one. If you haven't taken the SO tour, check it out here: stackoverflow.com/tour –  m59 Jan 24 '14 at 6:18

1 Answer 1

for..in is for iterating through object properties, read more here.

var array = [
  [1,2,3],
  [101,102,103]
];

for (var i=0; i<array.length; ++i) {
  var subArray = array[i];
  for (var j=0; j<subArray.length; ++j) {
    console.log(subArray[j]);
  }
}

You can also do this in modern browsers where forEach is available:

array.forEach(function(item, i) {
  item.forEach(function(subItem, i) {
    console.log(subItem);
  });
});

Live demo (click).

Regarding sorting, you would have to be more clear on what you want sorted - what goes in and what you want out.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.