getting rid of empty elements in array

Hello, after asking for a sorting-function in another thread, I decided to write my own function. The only thing it has to du is to get rid of empty elements in the array, by looking for objects inside the next element and moving them to the empty one.

This works fine for one empty element, but when it comes to two or more empty elements in a row, the function fails, because i’s not looking if the next element is empty too.

How do I write an good and short function for my issue? All in javascript.

function sortInventory(){
   for(var iii : int = 0;iii<inventory.Length-1;iii++){ 
 
      if(inventory[iii] == null){
 
          inventory[iii] = inventory[iii+1];
          inventory[iii+1] = null;
 
      }
 
   }
}

Instead of starting at the front and working forwards, why not start at the end and work backwards? Check the last element first… if it’s empty, remove it, then go to the next one in your for loop. I think this would work:

for (var iii: int = inventory.Length-1; iii > -1; iii--) {

Thank you! You just gave me the right direction … backwards :slight_smile:

Final function for everyone:

 function sortInventory(){

    for(var iSort : int = inventory.Length-1 ; iSort > 0 ; iSort--){    
 
       if(inventory[iSort] && !inventory[iSort-1]){
 
          inventory[iSort-1] = inventory[iSort];
          inventory[iSort] = null;
 
       }     
    }
 }