Coding for Scrubs: Moving Zeros to The End (JS)

Problem :

Pseudocode:

1. Create a for loop that will iterate through our given array
2. We want to start our iteration at the end of the array and make our way backwards
3. If a number is equal to 0, we would then want to use push() to push it to the end
4. We would want to use the splice() to move that 0 and update its index number
5. Return the array!

Building out the Function:

Writing the Function:

function moveZerosToEnd(arr){
}
function moveZerosToEnd(arr){
for(let i = arr.length-1; i>=0; i--){
}
}
function moveZerosToEnd(arr) {
for(let i= arr.length-1; i>=0; i--){
if(arr[i]===0){
arr.push(0)
arr.splice(i,1)
}
}
}

Conclusion:

function moveZerosToEnd(arr) {
for(let i= arr.length-1; i>=0; i--){
if(arr[i]===0){
arr.push(0)
arr.splice(i,1)
}
}
return arr
}
console.log(moveZerosToEnd([0,3,2,4,0,1,0]))

Software Engineer in the making.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store