开发者

AS3 numerical array sorting?

var dataArray:Array = [ 5, 6, 3, 8, 10, 11, 32, 2 ];
var dataObjectArray:Array [ { "uid": 5 }, { "uid": 6 .... Similar to above ... } ];

I have the above 2 arrays in AS3. and i wish to sort them numerically (1 ~ X) in order [Skipping th开发者_开发技巧ose that does not exist]. What is the best and most efficent way to do so for dataArray / dataObjectArray.

You may solve 1, or both =)


Have you tried:

dataArray.sort(  Array.NUMERIC );
dataObjectArray.sortOn( ["uid"], [Array.NUMERIC]); 


Surprisingly, as3 has in-built functions for this.

 dataArray.sort(Array.NUMERIC);
 dataObjectArray.sortOn("uid", Array.NUMERIC);

This would elegantly give the effect desired: Ascending order is by default. The array documentation covers additional details, such as descending order/etc... Lol sortOn even sorts nested objects / array if the field values are provided.


dataArray.sort();

Will automatically recognize if you're sorting numbers or strings and sort the array. But then I did something stupid. My array contains numbers as strings and then the sorting didn't work well when there were different number of digits when they're strings. So the winning solution is the full great answer:

dataArray.sort(  Array.NUMERIC );
dataObjectArray.sortOn( ["uid"], [Array.NUMERIC]);

If you want a reversed order (descending and not ascending order), then after sorting call:

dataArray.reverse();

Cheers!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜