Chris Ochsenreither
Chris Ochsenreither

Reputation: 75

print out elements of sub-array in Javascript

I don't understand how to find the length of a subarray in Javascript. Here is an example from an exercise:

 var table = [
["Person",  "Age",  "City"],
["Sue",     22,     "San Francisco"],
["Joe",     45,     "Halifax"]
];

I have tried to print out the elements of the sub-arrays individually using these for loops:

for(person in table) {
    for(var i = 0; i < table[person].length; i++);
        console.log(table[person][i]);
}

but it seems that

table[person].length

is not valid syntax although

table.length 

is valid and

table[person][i]

returns the element at the sub-index table_person_i

Upvotes: 1

Views: 5783

Answers (4)

PMG
PMG

Reputation: 190

That's an array, not an object, so you can't use for/ in loops. Use the regular for loop instead.

//for (person in table) {

for (var person = 1; person < table.length; person++) {
    for(var i = 0; i < table[person].length; i++)
    {
        console.log(table[person][i]);
    }
}

Upvotes: 1

Kaf
Kaf

Reputation: 33809

Try this:

for (var j = 0; j<table.length; j++) 
{
     //j(th) element of table array
     for (var i = 0; i < table[j].length; i++)
     {
         //i(th) element of j(th) element array
         console.log(table[j][i]);
     }
}

Upvotes: 1

Paul Rad
Paul Rad

Reputation: 4882

In your example, your array is an array of array. To fetch person's names, and according your example:

for (var i = 1; i < table.length; i++)
{
 console.log(table[i][0]); // first element of each sub array
}

Upvotes: 0

tymeJV
tymeJV

Reputation: 104775

You should use nested for loops for this task:

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

Upvotes: 1

Related Questions