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

I've been trying to iterate over a multidimensional array in JavaScript, and print each element in the array. Is there any way to print each element in a multidimensional array without using nested for-loops?

http://jsfiddle.net/mKsDW/

var arr = [[1, 5],[7, 4]];
for(var i in arr){
    alert(i); //this displays "0", then displays "1",
    //instead of printing each element in the array
    //how can I make it print each element in each 2D array instead,
    //without using nested for-loops for each dimension of the array?
}
share|improve this question
    
For arrays you should use a regular for loop instead of a for...in. And yes, it is possible to do without nested loops, but what's the point? Nested loops are the most readable and throughout solution. Other solutions would simply abstract one level of iteration. –  Fabrício Matté Apr 6 '13 at 18:21
    
@FabrícioMatté it would be very tedious to write nested for-loops for a 10 x 10 x 10 x 10 x 10 array, so I'd need a more concise solution. –  Anderson Green Apr 6 '13 at 18:23
    
Oh I see. Thought it was about 2D arrays only. –  Fabrício Matté Apr 6 '13 at 18:23

2 Answers 2

up vote 8 down vote accepted

Sounds like the issue is that you may have a nesting of arbitrary depth. In that case, use a recursive function.

function printArray(arr) {
    for (var i = 0; i < arr.length; i++)
        if (Array.isArray(arr[i]))
            printArray(arr[i])
        else
            console.log(arr[i])
}

The Array.isArray will need a shim for older browsers.

if (!Array.isArray)
    Array.isArray = function(o) {
        return !!o && Object.prototype.toString.call(o) === "[object Array]"
    }
share|improve this answer
    
Nice shim, I wonder though whether the truthy value check (!!o) is just a sanity check/optimization or is it actually necessary? –  Fabrício Matté Apr 6 '13 at 18:30
    
@FabrícioMatté: Yeah, it's not really needed. The toString part is usually the slowest, so if I really want to avoid it, I'd do !!o && typeof o === "object" && ... –  squint Apr 6 '13 at 18:32
    
I always use the MDN shim, but this one looks ok aswell (as it's basically the same) –  adeneo Apr 6 '13 at 18:33

If you don't want to use nested loops, you can either flat the array or use a recursive function. Something like:

arr.forEach(function each(item) {
  if (Array.isArray(item))
    item.forEach(each);
  else
    console.log(item)
});
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.