How do I move zeroes to the end of an array?

0 favourites
  • 5 posts
From the Asset Store
This is a code so you can see the same skin on all screens (peers). Each peer gets a skin, in addition to 4 directions t
  • I'm using a 2d array to create a team in a game, before going into battle, I want the team to all be pushed to the front of the array by moving zeroes to the end. This will keep the array the same size which is also important.

    Tagged:

  • Try Construct 3

    Develop games in your browser. Powerful, performant & highly capable.

    Try Now Construct 3 users don't see these ads
  • If you set the size to 0 then there would be no zeroes to push out, you can push the team to the front. If you want the zeroes back for some reason you can push 0 to the back of the array after the team.

  • If I set the size to 0, then wouldn't it delete the rest of the array's content?

  • kind of pain, and probably not the most efficient way, but I created functions that would send data to a different array from the first, only if it had data other than 0. Then cleared the first array and loaded the second array into the first.

  • Using a second array to temporarily hold values is a pretty straightforward, standard sorting technique.

    Alternatively, you can use a while loop, looking for array.indexof(0) to find 0, and delete that index. Keep track of how many 0s get deleted until there are none left, and push back that many times.

    Efficiency wise, you probably don't have to worry about it unless you're experiencing noticeable slowdowns.

Jump to:
Active Users
There are 1 visitors browsing this topic (0 users and 1 guests)