Created
January 19, 2015 20:43
-
-
Save nramirez/ccffcb0cf90e8f169eaf to your computer and use it in GitHub Desktop.
removeZeros_without_specials
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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