Skip to content

Instantly share code, notes, and snippets.

@nramirez
Created January 19, 2015 20:43
Show Gist options
  • Save nramirez/ccffcb0cf90e8f169eaf to your computer and use it in GitHub Desktop.
Save nramirez/ccffcb0cf90e8f169eaf to your computer and use it in GitHub Desktop.
removeZeros_without_specials
function removeZeros(array){
//Get initial zero index
var nextZero = getNextIndex(array,0);
var movedCounter = 0;
//If no zeros exists then we return the array
if (nextZero == -1) { return array};
while(nextZero < (array.length - movedCounter)){
//Copy the temporary zero, cause it could be a string or a number
var temp = array[nextZero];
move(array, nextZero);
//Asign the temp zero to the last position
array[array.length - 1] = temp;
//Count the numbers of zeros added to the end of the array
movedCounter++;
nextZero = getNextIndex(array,nextZero);
}
return array;
}
//This method move all the objects one position from the index position
function move(array, index){
for (var i = index; i < array.length -1; i++) {
array[i] = array[i + 1];
}
}
//This method provide a way to get the next zero index
//No matter if it is a number or a string
function getNextIndex(array, from){
var indexString = array.indexOf('0', from);
var indexInt = array.indexOf(0, from);
return indexString != -1 && (indexString < indexInt) ? indexString : indexInt;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment