Bummer! You must be logged in to access this page.

Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

increment through a multidimensional array

Im not quite sure how to go about doing this but is there a way to increment through a dimensional array one item at a time for instance if i want to increment through the second row one at a time with a button click how could i do this.

2 Answers

you can select elements in multidimensional arrays by using multiple [] selectors, like so:

var array = [["alpha","bravo","charlie"],["delta","echo","foxtrot"],["golf","hotel","india"]]

//this will return the second item of the second array, since arrays are 0-indexed
array[1][1]

To iterate over items with a button click, just add a counter and add to it as part of the event handler

var counter = 0
buttonElement.onclick = function() {
    var currentItem = array[1][counter];
    counter++
}

//or, using jquery

var counter = 0
$('#button').click(function() {
    var currentItem = array[1][counter];
    counter++
});

You could use a for loop.

for (var i = 0; i < arr[1].length; i++) {
    doSomething(arr[1][i]);
}