0

Say there's an array of arrays.

n = [ a = ["foo","bar"],
      b = ["foo2","bar2"],
      c = ["foo3","bar3"],
      d = ["foo4","bar4"],
      e = ["foo5","bar5"] ]

What's the simplest syntax to loop through all the foos and bars?

1
  • you can nested for loops Commented Jul 20, 2011 at 4:31

3 Answers 3

2

If you always have exactly 2 things in the inner arrays as per your example (fiddle - http://jsfiddle.net/pvqtz/):

for (var index = 0; index < n.length; index++) {
    var foobar = n[index];
    var foo = foobar[0];
    var bar = foobar[1];
    alert(foo + bar);
}

For an arbitrary number of things, use a nested loop (fiddle - http://jsfiddle.net/pvqtz/1/):

for (var index = 0; index < n.length; index++) {
    var innerArray = n[index];
    for (var innerIndex = 0; innerIndex < innerArray.length; innerIndex++) {
        var elem = innerArray[innerIndex];
        alert(elem);
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Nested loop. Exactly. Was like, on the tip of my brain or something. Thanks dude.
0

If your environment supports it, I tend to like forEach for this:

n.forEach(function(n2) { 
    n2.forEach(function(val) {
        console.log(val) 
    })
});

and just for the heck of it, if you're dealing with nested arrays of arbitrary depth, you can recurse:

function visit(a, f) {
    if (Array.isArray(a)) {
        a.forEach(function(a2) { 
            visit(a2, f)
        })
    } else f(a);
}

n = ["foo",["foo1", "bar1"], ["foo2", ["foo3","bar3"]]];
visit(n, function(val) { console.log(val) });

Comments

0

To iterate over foos and bars in one loop:

var i = -1;
while (i++ < n.length) 
    alert (n[i][0]+":"+n[i][1]);

or

for (var i = 0; i < n.length; i++) 
    alert (n[i][0]+":"+n[i][1]);

To iterate over all foos, then over all bars:

var i = -1, j = -1;
while (i++ < 2) 
    while (j++ < n.length) 
        alert (n[j][i]);

or

for (var i = 0; i < 2; i++) 
    for (var j = 0; j < n.length; j++) 
        alert (n[j][i]);

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.