Levi F.
Levi F.

Reputation: 91

2 dimensional matrix in JavaScript

Given the following array:

var list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];

and these for loops:

for (i = 0; i < 3; i++) {
    for (j = 0; j < 3; j++) {
       document.getElementById("someID").innerHTML = 
    }
} 

how can i print them in a 'textarea' having the following format:

1 2 3
4 5 6
7 8 9

Upvotes: 0

Views: 60

Answers (6)

Geeky Guy
Geeky Guy

Reputation: 9399

There are many ways to do that.

console.log will print one line per call on most browsers.

You can use line breaking characters ('\n') to print to a file, if you are working on an environment where you have access to IO (i.e.: NodeJS).

In HTML you can use the <br> tag, paragraphs (<p>), or you can place each line in a div. For example, with <br> you could do it like this:

var list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];

for (i = 0; i < list.length; i++) {
    document.getElementById("someID").innerHTML += list[i].join(" ") + "<br>";
}

Remember that each element of the outer array is an array itself, so you can print them as one element each with the join method from the Array type.

Upvotes: 0

Ingo B&#252;rk
Ingo B&#252;rk

Reputation: 20033

If it doesn't have to be for loops, you can also use map:

var list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]],
    someId = document.getElementById( 'someID' );

someId.innerHTML = '<pre>' + list.map(function (row) {
    return row.join(' '); 
}).join('<br>') + '</pre>';
<div id="someID"></div>

Upvotes: 1

Curtis Mattoon
Curtis Mattoon

Reputation: 4742

To display it in a div, you'll need to wrap each row in a div, because of how HTML handles whitespace:

See: JSFiddle

var list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
var html = '';
for (i = 0; i < list.length; i++) {
    html += list[i].join(' ');
}
document.getElementById('someID').innerHTML = html;

Upvotes: 0

prawn
prawn

Reputation: 2653

so maybe something like...

var list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];

var html = '';
for (i = 0; i < 3; i++) {
    for (j = 0; j < 3; j++) {
      html += list[i][j] + " ";               
    }
    html += '<br />';
} 
  
  document.getElementById("content").innerHTML = html;
<div id="content">
  
</div>

Upvotes: 0

Simply Craig
Simply Craig

Reputation: 1114

Something like this iterating through each idea:

add <div id="someID"></div>

Then instead of hard coding 3 use list.length and list[i].length then do:

var list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];

var temp = "";
for (i = 0; i < list.length; i++) {
    for (j = 0; j < list[i].length; j++) {
       temp+=list[i][j] + " ";
    }
    temp+="<br>";
} 
document.getElementById("someID").innerHTML = temp;

Working JSFiddle: http://jsfiddle.net/0k1tf5wh/

Hope this helps!!

Upvotes: 0

Some programmer dude
Some programmer dude

Reputation: 409166

Construct the string to output in the inner loops, and after the outer loop you make your element to show that string.

Upvotes: 0

Related Questions