linker85
linker85

Reputation: 1651

How to order an array of arrays by index in javascript

I'm trying to order an array of arrays by it's 2nd index, so if I have something like:

a[0][0] = #
a[0][1] = $
a[1][0] = x
a[1][1] = y
a[1][2] = z
a[2][0] = qaz
a[2][1] = qwerty

I get:

a[0][0] = #
a[1][0] = x
a[2][0] = qaz
a[0][1] = $
a[1][1] = y
a[2][1] = qwerty
a[1][2] = z

Thanks in advance!!

Upvotes: 2

Views: 306

Answers (1)

Kendall Frey
Kendall Frey

Reputation: 44374

This will display the elements in the required order.

var a = [["#", "$"], ["x", "y", "z"], ["qaz", "qwerty"]]
var maxLen = 0;
for (var i = 0; i < a.length; i++)
{
    maxLen = Math.max(maxLen, a[i].length);
}
for (var y = 0; y < maxLen; y++)
{
    for (var x = 0; x < a.length; x++)
    {
        if (y < a[x].length)
        {
            alert(a[x][y]); // You could use document.write() etc.
        }
    }
}

You didn't say what you intend to do with the array elements, but this general idea will work for displaying or printing them in order.

Upvotes: 3

Related Questions