espresso_coffee
espresso_coffee

Reputation: 6110

How to output elements from Javascript array in two different tables?

I have array with 44 elements. I want to output these elements in two different columns. First 32 elements should be in Table 1 and other 12 should be in Table 2. I would like to use one for loop for this if possible. So far I only found solution that required two for loops. Basically I would use .slice(). First loop will loop through myArray.slice(1,32) and second myArrat.slice(32,44). Here is my code:

var myArray = [1,2,3,4,5,6,7,8,....44];

for (var i = 0; i < myArray.slice(1,32); i++) {
    console.log(myArray[i]);
} 

for (var i = 0; i < myArray.slice(32,44); i++) {
    console.log(myArray[i]);
} 

Is there a way to do this in one loop? I would like to put them in two different dynamic created tables. Thanks in advance.

Upvotes: 0

Views: 37

Answers (1)

Joah Gerstenberg
Joah Gerstenberg

Reputation: 441

You can use a single for loop for this, though I don't see why you wouldn't just use the two .slice() calls.

You could do this:

var myArray = [1,2,3,4,5,6,7,8,....44];    

for (var i = 0; i < myArray.length; i++) {
    if (i < 32) {
        /* do something here */
    } else {
        /* do something else here */
    }
} 

Upvotes: 1

Related Questions