Easily sort an Array of Strings: Longest to Shortest Word

So let’s say you are making some sort of a game or program in Actionscipt 3 that requires you to sort words in order from longest to shortest. for example:

1
var word:Array = new Array("this", "is", "a", "list", "of", "randomly","chosen","words", "to", "sort");

if you try something like:

1
trace(word.sort());

you will get the following:

a,chosen,is,list,of,randomly,sort,this,to,words

That’s not what we wanted! A cool little thing that you can do in as3 is write what’s called a ‘compare function’. As I love to do, I have made a simple class with a static function that you call:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
package com.frigidfish{

    public class Sort {

        public function Sort() {
            // constructor code
        }

        public static function hiToLow(a:String, b:String):Number {


            if (a.length < b.length) {
                return 1;
            }
            else if (a.length > b.length) {
                return -1;
            }
            else {
                return 0;
            }
        }
    }
}

Now just save the class under your project in the correct folder (ie c:\myproject\com\frigidfish\Sort.as).

then, you can easily sort your array like so:

1
2
3
4
5
import com.frigidfish.Sort;

var word:Array = new Array("this", "is", "a", "list", "of", "randomly","chosen","words", "to", "sort");

trace(word.sort(Sort.hiToLow));

The output will now be:

randomly,chosen,words,list,this,sort,of,is,to,a

Yay!

You can use compare functions to tell the built in sort function how you would specifically like your data sorted.

The function takes 2 variables that are passed by the sort function (you don’t pass anything manually to the function. it’s automatic).

Because our array contains nothing but strings, we made up 2 variable names, ‘a’ and ‘b’; both of type string.

the function can return -1, 0 or 1. Depending on the return value, the sort will be affected. Experiment with different sorting methods and see what you can come up with..

For example, to sort low to high (short word to long word in our case) you would just add this function to the Sort class:

1
2
3
4
5
6
7
8
9
10
11
12
13
public static function lowToHigh(a:String, b:String):Number {


            if (a.length > b.length) {
                return 1;
            }
            else if (a.length < b.length) {
                return -1;
            }
            else {
                return 0;
            }
        }

of course you will also need to call the proper function now when you sort:

1
trace(word.sort(Sort.lowToHigh));

I hope this helps. Just had to use it in a project myself!

Share on FacebookShare on Google+Share on StumbleUponTweet about this on TwitterEmail this to someone

Facebook comments:

Leave a Reply