简体   繁体   中英

Sort an array but only the first X number of items in ActionScript?

I have an integer array and i need to sort the array but only the first 12 numbers. This is the code i have so far:

cantidad_bolillas_array = Bolillas_Array.length;
if(cantidad_bolillas_array > 12) {
    array1 = Bolillas_Array.slice(0, 12);
    array2 = Bolillas_Array.slice(12, cantidad_bolillas_array - 1);
    array1.sort();
    Bolillas_Array = array1.concat(array2);
}else{
    Bolillas_Array.sort();
}

but this is not working for me. What's the best way to accomplish this?

Just had to make a few changes, please see comments in updated code sample:

var cantidad_bolillas_array:Number = Bolillas_Array.length;
if(cantidad_bolillas_array > 12) {
    var array1:Array = Bolillas_Array.slice(0, 12);
    // when you use slice, remember that the endIndex is exclusive, not inclusive
    // that means you use "last index + 1" to get all the elements in the array
    var array2:Array = Bolillas_Array.slice(12, cantidad_bolillas_array);
    // make sure you sort numerically, otherwise you'll see stuff like 
    // "1, 11, 111, 2, 22, 222" etc
    array1.sort(Array.NUMERIC); 
    Bolillas_Array = array1.concat(array2);
}else{
    // once again, make sure to sort numerically
    Bolillas_Array.sort(Array.NUMERIC);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM