We'll start with your code.
var data = new Array(3)
data[0] = [4, "New Orleans",24];
data[1] = [7, "Houston",89];
data[2] = [2, "Los Angeles",47];
First, we need to sort the array so that they print by the order of the first column.
We can sort an array by calling array.sort(function(A, B) { /* comparator function */ })
. The comparator is any function taking two arguments that returns -1 if A is less than B, 1 if A is greater than B, and 0 if A and B are equal. You want to sort by the first column descending, so it looks like this:
data.sort((a, b) => (a[0] > b[0] ? 1 : -1));
This is fancy shorthand for saying that if the first element of a
is bigger than the first element of b
, return 1 (meaning that a
is larger); otherwise, return -1.
With array.sort
, your array is sorted in-place; after calling the sort
method it is permanently sorted (instead of, say, returning a sorted copy of the array).
Now we just create the table. Instead of using document.write()
, you should manipulate the DOM directly (see this question: Dynamic creation of table with DOM for reference).
What follows isn't the most efficient way of doing this, but should be the easiest for a beginner to follow:
var table = document.createElement('table');
for (var i = 0; i < data.length; i++) {
var tr = document.createElement('tr');
var td1 = document.createElement('td');
var td2 = document.createElement('td');
var td3 = document.createElement('td');
var text1 = document.createTextNode(data[i][0]);
var text2 = document.createTextNode(data[i][1]);
var text3 = document.createTextNode(data[i][2]);
td1.appendChild(text1);
td2.appendChild(text2);
td3.appendChild(text3);
tr.appendChild(td1);
tr.appendChild(td2);
tr.appendChild(td3);
table.appendChild(tr);
}
// Adds the table to the page so you see it -- up until this moment,
// we've just been preparing a table in memory.
document.body.appendChild(table);
And voila! The table appears.