Skip to content

Instantly share code, notes, and snippets.

@JiLiZART
Created October 12, 2017 23:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JiLiZART/dbc9ab10c29596ea7e42dcb698c16d22 to your computer and use it in GitHub Desktop.
Save JiLiZART/dbc9ab10c29596ea7e42dcb698c16d22 to your computer and use it in GitHub Desktop.
function shiftZeros(arr) {
var len = arr.length-1,
lastidx = len,
ZERO = 0;
for (var i = 0; i <= len; i++) {
if (lastidx <= i) break;
while (arr[lastidx] === ZERO) {
lastidx--;
}
var el = arr[i];
if (el === ZERO) {
arr[i] = arr[lastidx];
arr[lastidx] = el;
}
}
return arr
}
shiftZeros([1, 2, 3, 0, 4, 0, 0, 1, 0, 0]); // [1, 2, 3, 1, 4, 0, 0, 0, 0, 0]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment