pioSko
pioSko

Reputation: 551

Multidimensional array sort in AS3

What would be the easiest way to do a multi sort in AS3. Something similar to array_multisort() in PHP... like this: sort a multidimentional array using array_multisort

What I have

var COUNTRIES:Array = [["AD","Andorra"],["AE","United Arab Emirates"],["AF","Afghanistan"],["AG","Antigua & Barbuda"],["AI","Anguilla"]];

.. which looped outputs

Andorra
United Arab Emirates
Afghanistan
Antigua & Barbuda
Anguilla

... what I need is to sort it against the second index of each, so I get

Afghanistan
Andorra
Anguilla
Antigua & Barbuda
United Arab Emirates

Upvotes: 8

Views: 3731

Answers (4)

kapex
kapex

Reputation: 29959

It's simple:

 COUNTRIES.sortOn("1");

It works because you can access an array index by using a string, just like a property: array["0"]. So sortOn uses the "1" 'property' of each inner array for sorting.

Upvotes: 6

Corey
Corey

Reputation: 5818

You can use the Array.sort() method.

var COUNTRIES:Array = [[AD,Andorra],[AE,United Arab Emirates],[AF,Afghanistan],[AG,Antigua & Barbuda],[AI,Anguilla]];

COUNTRIES = COUNTRIES.sort(sortOnName);

function sortOnName(a:Array, b:Array):Number {
    var aName:String = a[1];
    var bName:String = b[1];

    if(aName > bName) {
        return 1;
    } else if(aName < bName) {
        return -1;
    } else  {
        //aName == bName
        return 0;
    }
}

Upvotes: 0

weltraumpirat
weltraumpirat

Reputation: 22604

You best create an array of Objects instead of an array of arrays, then use Array.sortOn:

var COUNTRIES : Array = 
    [ { short:"AD",long:"Andorra"}, 
      {short:"AE", long:"United Arab Emirates"}, 
      {short:"AF", long:"Afghanistan"}// and so forth
    ];

COUNTRIES.sortOn ("long"); // sorts by long name
COUNTRIES.sortOn ("short"); // sorts by short name

Upvotes: 0

PatrickS
PatrickS

Reputation: 9572

One way to achieve this would be to use an Array of Objects

  var countries:Array = [{abb:"AD", name:"Andorra"} //etc...];

You could then use the Array sortOn method.

Upvotes: 0

Related Questions