Skip to content

Instantly share code, notes, and snippets.

@edtoken
Created February 16, 2018 21:07
Show Gist options
  • Save edtoken/564234f5c8405cdd9bdfe342fcf2cc77 to your computer and use it in GitHub Desktop.
Save edtoken/564234f5c8405cdd9bdfe342fcf2cc77 to your computer and use it in GitHub Desktop.
Move all zeros to end.
function moveZeros(array) {
let i = 0;
let len = array.length;
let s = undefined;
let e = undefined;
while(i < len){
if(!array[i]){
if(s == undefined){
s = i;
e = i;
}else{
e = i;
}
i++;
continue;
}
if(s != undefined){
array[s] = array[i];
array[i] = 0;
i--;
if(s < e){
s ++;
}else{
s = undefined;
e = undefined;
}
}
i++;
}
return array;
}
alert(moveZeros([0,1,4,0,0,0,2,2,2,2,2,0,0,10]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment