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

Welcome back to Coding for Scrubs! Today we will be talking about how to search through an array of numbers and move all the 0s to the end of our array. This is a fairly simple problem, but fun to do! This challenge is an easy level whiteboarding problem that I found on Leetcode.

Problem :

Given an array nums, write a function to move all 0’s to the end of it while maintaining the relative order of the non-zero elements.

Example:
Input: [0,1,0,3,12]
Output: [1,3,12,0,0]

Note:
You must do this in-place without making a copy of the array.
Minimize the total number of operations.

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:

Let’s go ahead and create our function and call it moveZerosToEnd and pass in an arr (array) as our argument.

function moveZerosToEnd(arr){
}

We know we have to iterate through our array of numbers, so we begin to write our for loop. In our for loop, we want to start at the end of the array and make our way backward. We have to set i to start at the end of our array, hence arr.length-1.

Note: Indexes start at 0 and that’s why we have to subtract 1!

function moveZerosToEnd(arr){
for(let i = arr.length-1; i>=0; i--){
}
}

Time for our conditional statement! If the number in our arr is equal to 0, we want to then push that 0 to the end of our array. We would also want to use splice() to replace the number in that array to carry a new index number.

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

Lastly, we have to return our new arr!

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.