hazdog
hazdog

Reputation: 121

AS3: Sort array descending while keeping strings in correct order

I'm not sure whether there is a simply answer to this but I am assuming there isn't, hence I'm here.

Basically, I want to run a very simple high score table which keeps track of the high scores of a game, but also displays the correct names beside each scores.

This is all easy but I want to be able to do this with just the one array.

For example, I have this code:

var d:Array;
var e:Array;
d = "827-Harry".split("-");
d.push("918-John".split("-"));
trace(d)

Which correctly results this trace:

827,Harry,918,John

My question is, how can I use Array.sort() (or similar) in such a way that the following is produced:

d = 918, John, 827, Harry

It can't be specific to this example. That is, it needs to work with custom names and dynamic scores.

Cheers in advance! Harry.

Upvotes: 0

Views: 5320

Answers (2)

xLite
xLite

Reputation: 1481

Wouldn't recommend you store your high scores like that but I don't know your reasons so here's exactly how to do what you want.

public function sortArray(arrUnsorted:Array):Array
{
    var arrLocal:Array = new Array();
    var arrSorted:Array = new Array();

    for (var i:int = 0; i < arrUnsorted.length; i += 2)
    {
        arrLocal.push( { score:int(arrUnsorted[i]), name:arrUnsorted[i + 1] } );
    }

    arrLocal.sortOn("score", Array.DESCENDING | Array.NUMERIC)

    for each(var obj:Object in arrLocal)
    {
        arrSorted.push(String(obj.score), obj.name);
    }

    return arrSorted;
}

Then it's as simple as:

var arrUnsorted:Array = ["827", "Harry", "918", "John"];
var arrSorted:Array = sortArray(arrUnsorted);

trace(arrSorted); // 918,John,827,Harry

Hope this is what you're after.

Upvotes: 0

Chunky Chunk
Chunky Chunk

Reputation: 17217

create an associative array and use sortOn():

var highscores:Array = new Array();
highscores.push({score: 827, player: "John"});
highscores.push({score: 918, player: "Harry"});
highscores.sortOn("score", Array.DESCENDING | Array.NUMERIC);

for (var i:int = 0; i < highscores.length; i++)
{
    trace(highscores[i].score, highscores[i].player);
}

Upvotes: 4

Related Questions