# JavaScript | Move Zeroes

## Interview Question

This question comes under a broad category of “Array Transformation”.

Given an integer array `nums`

, move all `0`

's to the end of it while maintaining the relative order of the non-zero elements.

**Note** that you must do this in-place without making a copy of the array.

**Example:**

**Input:** nums = [0,1,0,3,12]

**Output:** [1,3,12,0,0]

**Solution**:

The 2 requirements of the question are:

- Move all the 0’s to the end of array.
- All the non-zero elements must retain their original order.

Let's look into two implementation -

In the first implementation,

- the first loop deletes the zeros using splice().
- the second loop pushes the zeros to the end of arrays using push().

var moveZeroes = function(nums) {

let zeros = 0 for (let i = 0; i < nums.length; i++) {

let isZero = nums[i] === 0

if (isZero){

zeros++

nums.splice(i, 1)

i--

}

} for (let i = 0; i < zeros; i++){

nums.push(0)

} return nums

};

Second Implementation,

- using one for loop, we will delete the zeros using splice() and push the zeros to the end of the array using push().

`var moveZeroes = function(nums) {`

for (let i = nums.length - 1; i >= 0; i--) {

nums[i] === 0 && nums.splice(i, 1) && nums.push(0);

}

return nums

};

Summary

- use splice() method of the array, to delete the zeros and add those zeros to the end of the array using push().

This problem is very popular in coding interviews.

Keep learning, keep growing!

Don’t forget to follow me for more such articles, and subscribe to our newsletter.

Let’s connect on LinkedIn!. Please read more for more ** data structure javascript question**.

Don’t forget to follow The Lean Programmer Publication for more such articles, and subscribe to our newsletter tinyletter.com/TheLeanProgrammer