|
-
file not found
[MX04] [AS2] Sort an array by integers?
So, I think I'm going to have to end up writing a custom function for this, but I wanted to check here first to make sure I'm not doing a ton of work for nothing.
The array.sort() function does a fine job of sorting array by the value of the string, but when it comes to putting numbers in the right order it falls short because it tries to sort them as strings.
So the array [5,7,14,300] would end up sorted as [14,300,5,7] which is obviously not what I want.
So is there any way to get it to sort only based on the integer property or there an entirely different function that can do what I want?
-
file not found
This always seems to happen when I post here, I find the answer within an hour after I post...
I went ahead and wrote my own function for it because I have nothing better to do right now, if anyone wants to look over it I'd love to hear if I could do anything better or more efficiently.
Also, if there's a function to do this already, it would be great to know, there's much less typing involved that way...
PHP Code:
x = [random(30),random(30),random(30),random(30)];
x2 = [x[0]];
for (n=1;n<x.length;n++) {
temp = x[n];
trace(temp);
for (n2=0;n2<x2.length;n2++) {
if (n2 == 0 and temp < x2[n2]) {
trace(temp+" < "+x2[n2]);
x2.splice(n2,0,temp);
break;
} else if (temp < x2[n2] and temp < x2[n2+1]) {
trace(x2[n2]+" < "+temp+" < "+x2[n2+1]);
x2.splice(n2,0,temp);
break;
} else if (n2 == x2.length-1) {
if (temp < x2[n2]) {
x2.splice(n2,0,temp);
} else {
x2.push(temp);
}
break;
}
}
trace("");
}
trace(x);
trace(x2);
-
the sort method takes a (horrendously) ambiguous argument that can specify to sort numerically:
Code:
yourArray.sort( Array.NUMERIC );
the Array sort type enumeration are uints that each represent a bit flag that gets set on the sort criteria. so to sort both numerically, and order the sort to descend instead of ascend you use the bitwise OR operator:
Code:
yourArray.sort( Array.NUMERIC | Array.DESCENDING );
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|