Adam Edney
Adam Edney

Reputation: 310

AS3 Multidimensional array sorting

Is there a way to sort a multidimensional array. I want to sort it by the second dimension.

so for example.....

    array[0][1] = 5
    array[1][1] = 20
    array[2][1] = 10

And I want the output to be 5 , 10 , 20

I tired a few experiments with little / no success. e.g.

array.sortOn("1", 0, Array.NUMERIC);

Any ideas?

Upvotes: 1

Views: 177

Answers (2)

Aaron Beall
Aaron Beall

Reputation: 52133

Your second argument is a 0, it should be your array options. Example:

var array:Array = [
    [1, 100],
    [2, 50],
    [3, 75]
]

array.sortOn("1", Array.NUMERIC)
trace(array.join("\n"))

array.sortOn("0", Array.NUMERIC);
trace(array.join("\n"))

Results:

2,50
3,75
1,100

1,100
2,50
3,75

Upvotes: 1

Patrick Gunderson
Patrick Gunderson

Reputation: 3281

You can use a custom sort function

var myArray = [[0,5],[0,20],[0,10]];
var sorted = myArray.sort(function(a:Array,b:Array):Number{
    return a[1] - b[1];
});

Upvotes: 1

Related Questions