2

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!!

8
  • 1
    Do you know the sort() function? Commented Apr 19, 2012 at 16:39
  • 7
    OK, so what have you tried? This site is not for other people to write all your code for you. Commented Apr 19, 2012 at 16:39
  • 1
    I know the sort function but doesn´t that sort it by value instead of by index??? Commented Apr 19, 2012 at 16:40
  • 1
    @linker85 Do you know that the sort function takes an optional argument which is a function that allows you to do custom sorting? Commented Apr 19, 2012 at 16:42
  • Are you actually trying to sort, or just loop through the arrays and output the values? Commented Apr 19, 2012 at 16:45

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

You can also use this technique to insert the elements into a new array that will preserve the sort order that you need.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.