[Question]
  [
The task is simple: consolidate an array of ints. Consolidating this array consists of the following:
* All instances of 0 need to be moved to the end of the array.
* There should be no 0s between the non-zero integers.
* All non-zero indices should retain their order.
# Challenge
Consolidate an array in the least amount of bytes.
You are consolidating an array of random length with a size up to your language's max with random integers. Input may be any natural way for your language.
# Examples
Input
```
0 5 8 8 3 5 1 6 8 4 0 3 7 5 6 4 4 7 5 6 7 4 4 9 1 0 5 7 9 3 0 2 2 4 3 0 4 8 7 3 1 4 7 5 1 2 1 8 7 8 7 7 2 6 3 1 2 8 5 1 4 2 0 5 0 6 0 3
```
Output
```
5 8 8 3 5 1 6 8 4 3 7 5 6 4 4 7 5 6 7 4 4 9 1 5 7 9 3 2 2 4 3 4 8 7 3 1 4 7 5 1 2 1 8 7 8 7 7 2 6 3 1 2 8 5 1 4 2 5 6 3 0 0 0 0 0 0 0 0
```
Input
```
-1 -7 -6 5 1 -5 -2 7 -3 -8 0 8 9 1 -8 -1 6 -4 1 -2 1 -7 5 4 -6 7 -3 9 8 3 -1 0 -5 -7 3 8 1 1 3 -3 -2 -2 0 -7 0 -4 8 6 -3 6 0 5 3 2 2 2 -2 -7 -3 9 -1 6 0 6 -7 9 4 -2 8 -8 -4 1 -8 4 3 7 3 5 1 0 3 3 7 -1 -5 1 -3 4 -7 0 3 2 -2 7 -3 0 0 2 -5 8 -3 -2 -7 -5 7 -3 -9 -7 5 8 -3 9 6 7 -2 4 7
```
Output
```
-1 -7 -6 5 1 -5 -2 7 -3 -8 8 9 1 -8 -1 6 -4 1 -2 1 -7 5 4 -6 7 -3 9 8 3 -1 -5 -7 3 8 1 1 3 -3 -2 -2 -7 -4 8 6 -3 6 5 3 2 2 2 -2 -7 -3 9 -1 6 6 -7 9 4 -2 8 -8 -4 1 -8 4 3 7 3 5 1 3 3 7 -1 -5 1 -3 4 -7 3 2 -2 7 -3 2 -5 8 -3 -2 -7 -5 7 -3 -9 -7 5 8 -3 9 6 7 -2 4 7 0 0 0 0 0 0 0 0 0 0
```
# Example Code (Java)
```
public class Consolidate {
    public static void main(String[] args) throws Exception {
        int[] toConsolidate = new int[args.length];
        for (int i=0; i<args.length; i++){
            toConsolidate[i]=Integer.parseInt(args[i]);
        }
        for (int i=0; i<toConsolidate.length; i++) {
            for (int k=0; k<toConsolidate.length-1; k++) {
                if (toConsolidate[k] == 0){
                    toConsolidate[k] = toConsolidate[k+1];
                    toConsolidate[k+1] = 0;
                }
            }
        }
        for (int i:toConsolidate)
            System.out.print(i+" ");
    }
}
```
  
[Answer]
## Pyth, 3 bytes
```
!DQ
```
Explanation:
```
  Q    Input
!D     Sort by logical NOT
```
Try it [here](http://pyth.herokuapp.com/?code=%21DQ&input=%5B0%2C+5%2C+8%2C+8%2C+3%2C+5%2C+1%2C+6%2C+8%2C+4%2C+0%2C+3%2C+7%2C+5%2C+6%2C+4%2C+4%2C+7%2C+5%2C+6%2C+7%2C+4%2C+4%2C+9%2C+1%2C+0%2C+5%2C+7%2C+9%2C+3%2C+0%2C+2%2C+2%2C+4%2C+3%2C+0%2C+4%2C+8%2C+7%2C+3%2C+1%2C+4%2C+7%2C+5%2C+1%2C+2%2C+1%2C+8%2C+7%2C+8%2C+7%2C+7%2C+2%2C+6%2C+3%2C+1%2C+2%2C+8%2C+5%2C+1%2C+4%2C+2%2C+0%2C+5%2C+0%2C+6%2C+0%2C+3%5D&debug=0).
[Answer]
# Jelly, 3 bytes
```
¬Ụị
```
Sorts the list by the logical NOT of its values. [Try it online!](http://jelly.tryitonline.net/#code=wqzhu6Thu4s&input=&args=WzAsIDUsIDgsIDgsIDMsIDUsIDEsIDYsIDgsIDQsIDAsIDMsIDcsIDUsIDYsIDQsIDQsIDcsIDUsIDYsIDcsIDQsIDQsIDksIDEsIDAsIDUsIDcsIDksIDMsIDAsIDIsIDIsIDQsIDMsIDAsIDQsIDgsIDcsIDMsIDEsIDQsIDcsIDUsIDEsIDIsIDEsIDgsIDcsIDgsIDcsIDcsIDIsIDYsIDMsIDEsIDIsIDgsIDUsIDEsIDQsIDIsIDAsIDUsIDAsIDYsIDAsIDNd)
### How it works
```
¬Ụị    Main link. Input: A (list)
¬      Compute the logical NOT of each element of A.
 Ụ     Grade up; sort the resulting list's indices by their corresponding values.
  ị    Retrieve the elements of A at that indices.
```
[Answer]
# Octave, 18 bytes
```
@(A)[A(~~A) A(~A)]
```
`sort()` takes too many bytes. I'll just use logical indexing.
Examples on [ideone](http://ideone.com/yXZ7cp).
[Answer]
# R, ~~29~~ ~~23~~ 21 bytes
As noted by MarcoBreitig, we can shorten it to 21 bytes if we don't need to provide it as a function:
```
x=scan();x[order(!x)]
```
---
Previous versions:
```
function(x)x[order(!x)]
```
The function takes a vector as input and orders by the logical vector that results from negating the input.
Original answer:
```
function(x)c(x[x!=0],x[x==0])
```
The function takes a vector as input and the concatenates (`c()`) the non-zero values and then the zero-values.
[Answer]
# [Retina](http://github.com/mbuettner/retina), 15
Simple repeated regex substitution:
```
+`\b0 (.*)
$1 0
```
[Try it online.](http://retina.tryitonline.net/#code=K2BcYjAgKC4qKQokMSAw&input=MCA1IDggOCAzIDUgMSA2IDggNCAwIDMgNyA1IDYgNCA0IDcgNSA2IDcgNCA0IDkgMSAwIDUgNyA5IDMgMCAyIDIgNCAzIDAgNCA4IDcgMyAxIDQgNyA1IDEgMiAxIDggNyA4IDcgNyAyIDYgMyAxIDIgOCA1IDEgNCAyIDAgNSAwIDYgMCAz)
[Answer]
## Python, 32 bytes
```
lambda x:sorted(x,key=0..__eq__)
```
Takes argument as any iterable (list, tuple, etc.). Thanks to @xnor for teaching me a new trick!
[Answer]
## ES6, 23 bytes
```
a=>a.sort((x,y)=>!x-!y)
```
It used to be the case that `sort` wasn't stable, in which case you needed 41 bytes:
```
a=>a.filter(x=>x).concat(a.filter(x=>!x))
```
[Answer]
# Python byte code (2.7.9), 252 bytes, 33 opcodes, 0.0228 seconds
This was build when the contest was still a [fastest-code](/questions/tagged/fastest-code "show questions tagged 'fastest-code'") contest
Opens a file in the current directory called `'SourceArray'` for use
```
LOAD_CONST          ''
STORE_FAST          no_zeroes#  no_zeroes = ''
LOAD_NAME           open
LOAD_CONST          'SourceArray'
CALL_FUNCTION       0,1#  open('SourceArray')
LOAD_ATTR           read
CALL_FUNCTION       0,0#  .read()
LOAD_ATTR           split
CALL_FUNCTION       0,0#  .split()
DUP_TOP
DUP_TOP             #Start if
BUILD_LIST          0
COMPARE_OP          ==
POP_JUMP_IF_TRUE    35#  if list == [], GOTO 35
LOAD_ATTR           pop
LOAD_CONST          0
CALL_FUNCTION       0,1#  list.pop(0)
DUP_TOP
LOAD_CONST          '0'
COMPARE_OP          ==
POP_JUMP_IF_TRUE    28#  if list.pop(0) == '0', GOTO 28
PRINT_ITEM          #  print list.pop(0)
JUMP_ABSOLUTE       13
POP_TOP
LOAD_CONST          '0%_'#  '0 '
LOAD_FAST           no_zeroes
INPLACE_ADD
STORE_FAST          no_zeroes#  no_zeroes = no_zeroes + '0 '
JUMP_ABSOLUTE       13
LOAD_FAST           no_zeroes
PRINT_ITEM          #  print no_zeroes
LOAD_CONST          None
RETURN_VALUE
```
The `co_code` (The actual codey bit)
```
'd\x01\x00}\x00\x00\te\x00\x00\x83\x00\x00\tj\x01\x00\x83\x00\x00\t\x04\x04g\x00\x00k\x02\x00sG\x00j\x02\x00d\x02\x00\x83\x01\x00\x04d\x03\x00k\x02\x00s8\x00Gq\x15\x00\t\x01d\x04\x00|\x00\x007}\x00\x00q\x15\x00\t|\x00\x00G\td\x00\x00S'
```
Or a .pyc file version `03F3`
```
03 F3 0D 0A 40 FD B0 56 63 00 00 00 00 01 00 00 00 03 00 00 00 00 00 00 00 73 59 00 00 00 64 01 00 7D 00 00 09 65 00 00 64 02 00 83 01 00 6A 01 00 83 00 00 09 6A 02 00 83 00 00 09 04 04 67 00 00 6B 02 00 73 50 00 6A 03 00 64 03 00 83 01 00 04 64 04 00 6B 02 00 73 41 00 47 71 1E 00 09 01 64 05 00 7C 00 00 37 7D 00 00 71 1E 00 09 7C 00 00 47 09 64 00 00 53 28 06 00 00 00 4E 74 00 00 00 00 74 0B 00 00 00 53 6F 75 72 63 65 41 72 72 61 79 69 00 00 00 00 74 01 00 00 00 30 73 02 00 00 00 30 20 28 04 00 00 00 74 04 00 00 00 6F 70 65 6E 74 04 00 00 00 72 65 61 64 74 05 00 00 00 73 70 6C 69 74 74 03 00 00 00 70 6F 70 28 01 00 00 00 74 09 00 00 00 6E 6F 5F 7A 65 72 6F 65 73 28 00 00 00 00 28 00 00 00 00 74 09 00 00 00 70 79 6B 65 5F 63 6F 64 65 52 08 00 00 00 01 00 00 00 52 00 00 00 00
```
You can try to compile my source code yourself using [my library on github.](https://github.com/muddyfish/Python-PYKE) I just posted a commit to it that allowed comments so I hope this is still competing as far as [fastest-code](/questions/tagged/fastest-code "show questions tagged 'fastest-code'") goes ;)
Roughly equivalent to
```
no_zeroes = ''
unamed_variable = open('SourceArray').read().split()
while unamed_variable != []:
    unamed_variable_2 = unamed_variable.pop()
    if unamed_variable_2 == '0':
        no_zeroes += '0 '
    else:
        print unamed_variable_2,
print no_zeroes,
```
[Answer]
# Matlab: 21 bytes
```
@(a)[a(a~=0),a(a==0)]
```
Prints nonzero elements first, then concatenates with zero elements
`@(a)____` create an anonymous function with one input argument `a`
`[___,___]` concatenates horizontally vectors inside brackets, separated by commas
`a(a~=0)` returns vector with all nonzero elements of vector `a`
`a(a==0)` returns vector with all zero elements of vector `a`
[Answer]
# APL: 8 bytes
```
(⍴a)↑a~0
```
a~0 remove zeros from a (read "a without 0")  
(⍴a) original length of a (read "shape of a")  
↑ pad a without zeros to a's original length
Try it in <http://ngn.github.com/apl/web/index.html>
Test data: a←1 0 1 2 3 4 0 1 0 0 0 0 1 2 3 4 5
[Answer]
# Zsh, 22 bytes
(input passed as arguments to the script/function (`$@` aka `$argv` array), output on stdout as space separated list, newline terminated)
```
<<<${@:#0}\ ${(M)@:#0}
```
* `<<< string`: here-string here passed as stdin to the `$NULLCMD` command (`cat` by default).
* `${@:#0}` `$@` except elements being 0.
* `${(M)@:#0}` reverse of the above
That assumes (like several other answers here) that zeroes in the input are all expressed as `0` (no `00` nor `0x0` nor `36#0`).
[Answer]
## Haskell, 26 bytes
```
f x=filter(/=0)x++[0|0<-x]
```
Take all non-zero numbers followed by all zeros. Filtering constants (here: `0`) is quite short when using a list comprehension: `[0|0<-x]`.
[Answer]
# Mathematica, 14 bytes
```
Sort[#,#!=0&]&
```
[Answer]
# Common Lisp, 46 bytes
```
(lambda(a)(stable-sort a(lambda(_ b)(= 0 b))))
```
Sort the array so that for each couple *(a,b)*, we have *a < b* if *b* is zero. When neither *a < b* or *b < a*, the sort is stable: the original order between elements is retained.
I also tried with *adjust-array* and *remove*, but this was too long:
```
(lambda(a)(adjust-array(remove 0 a)(length a):initial-element 0))
```
[Answer]
# Javascript, ~~52~~ ~~54~~ 51 bytes
```
s=>s.replace(/\b0 /g,x=>++i&&'',i=0)+' 0'.repeat(i)
```
[Answer]
## Java 7, 78 bytes
```
void g(int[]a){int c=0;for(int o:a)a[o==0?c:c++]=o;for(;c<a.length;a[c++]=0);}
```
I'm not sure why the other Java entries are using strings. If you want to filter an integer array, it seems best to use an integer array. This modifies the input in place by keeping two indices, then just filling the remaining slots with zeros.
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), ~~3~~ 2 bytes
```
µ¬
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%C2%B5%C2%AC&inputs=0%205%208%208%203%205%201%206%208%204%200%203%207%205%206%204%204%207%205%206%207%204%204%209%201%200%205%207%209%203%200%202%202%204%203%200%204%208%207%203%201%204%207%205%201%202%201%208%207%208%207%207%202%206%203%201%202%208%205%201%204%202%200%205%200%206%200%203&header=%3F%C3%B0%2FvI&footer=)
Sort by logical negation. The header puts the input into a list format.
[Answer]
# PHP, ~~73~~ ~~71~~ ~~70~~ ~~52~~ ~~49~~ ~~48~~ 46 bytes - BIG thanks to [Ismael Miguel](https://codegolf.stackexchange.com/users/14732)
```
// Assuming
$a = array(4,8,6,1,0,8,0,0,0,0,0,-4,'-5',-1,564,0);
// Produces a notice-level error
foreach($a as$v)$v?print"$v ":$b.="0 ";echo$b;
```
[Answer]
# Bash + GNU utilities, 23
```
grep -v ^0 a
grep ^0 a
```
Assumes input is newline-separated entries in a file called `a`. Score includes +1 for this filename.
[Answer]
# Perl 5, 26 bytes
23 plus three for `-an` (`-E` is free)
```
say for sort{!$a-!$b}@F
```
Thanks to [Dennis](/u/12012) for reminding me of `-a`, saving two bytes.
[Answer]
# JavaScript ES6, 16 bytes
```
x=>x.sort(t=>!t)
```
Works on firefox
[Answer]
# [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 34 bytes
```
{for(;a++-NF;c?$++b=c:0)$a-=c=$a}1
```
[Try it online!](https://tio.run/##NY@xDsIwDER/xUMHUGTJTVLiUlVsjPxDqMTCgMTCgPj24HNAqdqec34@19e9tfft8dwtNQS@nJftNIRwXbej7IfK67YO9TO2xiNxIT7QRPY3EUcymYiVhJRmVJXMdSDOEJG8Y6KMLvfOZkzwiBOKCTXXiGJChz2CuoChQCV7iUESRT8w/Vg@S2AqpjKu1DPkniVbE0YgsNgXij37CEDug1KHOlPsRBj0n6dA9T3nvo324b5RNEj5Ag "AWK – Try It Online")
This code runs through all the commandline arguments, shifts non-zero values to the left and clears arguments as it processes them.
The top of loop "should we iteration" condition expression is:
```
a++-NF
```
which increments `a` until it hits the number of commandline arguments `NF`.
The body of the loop,
```
$a-=c=$a
```
saves the value of the current commandline argument in variable `c`, then sets the current argument to 0.
At the end of each iteration, the ternery:
```
c?$++b=c:0
```
checks to see if the current argument `c` is non-zero and if so, increments the `b` (the number of non-zero argument found so far) and stores the current argument value in that slot.
After the code block processes the commandline arguments, the only left to do is trigger AWK to print all the commandline arguments with a `truthy` test without a code block.
```
1
```
[Answer]
# [Uiua](https://uiua.org), 5 [bytes](https://www.uiua.org/pad?src=U0JDUyDihpAgK0BcMOKKlwpEZWNvZGUg4oaQIOKHjOKKjy0x4pa9wrEu4o2Y4ouv4oav4oqCwq8x4qe74ouv4qe7LOKHjOKItSjihpjCrzHii68rMjU2KSAtQFwwKzEKJnAg4oqCIjggYml0IGVuY29kaW5nOlx0IiBTQkNTICLih4ziio8tMeKWvcKxLuKNmOKLr-KGr-KKgsKvMeKnu-KLr-Knuyzih4ziiLUo4oaYwq8x4ouvKzI1NikiIOKKgitAXDDih6ExMjkiLiziiLY74oiYwqzCscKv4oy14oia4peL4oyK4oyI4oGFPeKJoDziiaQ-4omlKy3Dl8O34pe_4oG_4oKZ4oan4oal4oig4qe74paz4oeh4oqi4oeM4pmt4ouv4o2J4o2P4o2W4oqa4oqb4oqd4pah4oqU4omF4oqf4oqC4oqP4oqh4oav4oaZ4oaY4oa74per4pa94oyV4oiK4oqXL-KIp1xc4oi14omh4oi64oqe4oqg4o2l4oqV4oqc4oip4oqT4oqD4oqZ4ouF4o2Y4o2c4o2a4qyaJz_ijaPijaQh4o6L4oas4pqCzrfPgM-E4oiefl9bXXt9KCnCr0AkXCLihpB8IyIKJnAg4oqCImRlY29kZWQ6XHQiIERlY29kZSAiwqPCsS0xwrjChy7DjMKlwrPCsMKIMcKfwqXCnyzCo8K_KMK1wogxwqUrMjU2KSIg4oqCK0BcMOKHoTEyOSIuLOKItjviiJjCrMKxwq_ijLXiiJril4vijIrijIjigYU94omgPOKJpD7iiaUrLcOXw7fil7_igb_igpnihqfihqXiiKDip7vilrPih6HiiqLih4zima3ii6_ijYnijY_ijZbiipriipviip3ilqHiipTiiYXiip_iioLiio_iiqHihq_ihpnihpjihrvil6vilr3ijJXiiIriipcv4oinXFziiLXiiaHiiLriip7iiqDijaXiipXiipziiKniipPiioPiipnii4XijZjijZzijZrirJonP-KNo-KNpCHijovihqzimoLOt8-Az4TiiJ5-X1tde30oKcKvQCRcIuKGkHwjIg==)
```
⊏⍏=0.
```
[Try it!](https://uiua.org/pad?src=ZiDihpAg4oqP4o2PPTAuCgpmIFsxIDAgMiAwIMKvNSAwIDMgNCA1IDAgMCA2XQ==)
```
⊏⍏=0.
    .  # duplicate
  =0   # where is it equal to zero?
 ⍏     # rise (grade up)
⊏      # select
```
[Answer]
# CJam, 6 bytes
```
{{!}$}
```
An anonymous function. Sort using “whether or not an element is zero” as a key.
[Answer]
# Clojure/ClojureScript, 18 bytes
```
#(sort-by zero? %)
```
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), 7 bytes
```
t~FT#S)
```
[**Try it online!**](http://matl.tryitonline.net/#code=dH5GVCNTKQ&input=WzAgNSA4IDggMyA1IDEgNiA4IDQgMCAzIDcgNSA2IDQgNCA3IDUgNiA3IDQgNCA5IDEgMCA1IDcgOSAzIDAgMiAyIDQgMyAwIDQgOCA3IDMgMSA0IDcgNSAxIDIgMSA4IDcgOCA3IDcgMiA2IDMgMSAyIDggNSAxIDQgMiAwIDUgMCA2IDAgM10)
```
t      % input array. Duplicate
~      % logical negate: nonzero values become false, zeros become true
FT#S   % sort (false, then true) and output a vector with the indices of the sorting
)      % apply that vector of indices to original array
```
[Answer]
## Seriously, 12 bytes
```
4,n`Y`M@░)░+
```
[Try it online!](http://seriously.tryitonline.net/#code=NCxuYFlgTUDilpEp4paRKw&input=WzEsMiwwLDMsMV0)
Explanation:
```
4,n`Y`M@░)░+
4,n           push 4 copies of input
   `Y`M       map logical negate
       @░)    filter (take zeroes) and push to bottom of stack
          ░   filter (take non-zeroes)
           +  append zeroes
```
[Answer]
# [Swift](https://swift.org/), 13 bytes
```
a.sort{$1==0}
```
[Answer]
# Perl6, 11 bytes
```
{.sort(!*)}
```
Produces a Block - which can be called on an array:
```
{.sort(!*)}.([1,2,0,3]).say
```
Although it would be more natural (and shorter) to write:
```
[1,2,0,3].sort(!*).say
```
How it works: if the [perl6 sort routine](http://doc.perl6.org/routine/sort) is called with a block which accepts only one argument, the list elements are sorted according to `by($a) cmp by($b)`. In this case, the block is `!*`, i.e. a negation of the [whatever operator](http://doc.perl6.org/routine/*#language_documentation_Terms).
I notice that:
* The example in the question is a class which provides a method, not including boilerplate required to read in
* The description of the task does not require printing, and, except for the fact that the example prints, implies that an array might be returned
[Answer]
## TeX (Plain format), 160 bytes
Make the `0` character active (that is, make the interpreter process it as a command), then define that command to skip the character and increment a counter. At the end of the string, print as many zeros as were counted.
Save this as `zero.tex` and give the input through the command line with this command:
```
pdftex "\def\I{0 1 0 3 2 0 0 8 0 5 0 1 9 4}\input zero"
```
```
\def\I{}\newcount\Z\def\L{\loop\advance\Z by-1\ifnum\Z>00 \repeat}
\begingroup\catcode`\013 \def0{\advance\Z by1}
\scantokens\expandafter{\I\empty}\endgroup\L\bye
```
(Newlines added for clarity)
[![enter image description here](https://i.stack.imgur.com/FlHOU.png)](https://i.stack.imgur.com/FlHOU.png)
]