Skip to content

Instantly share code, notes, and snippets.

@psenger
Created December 1, 2023 02:22
Show Gist options
  • Select an option

  • Save psenger/bea5146a71ee679dd75e84ccb736cf30 to your computer and use it in GitHub Desktop.

Select an option

Save psenger/bea5146a71ee679dd75e84ccb736cf30 to your computer and use it in GitHub Desktop.
[Destructuring Assignment] #JavaScript #Array #
/**
* Function: moveZeros
* Description: This function moves all zeros in an array to the end of the array, while
* preserving the order of the other elements. Without creating a new Array.
* Note: this uses a common two-pointer method, is O(n) and does not create a new array
* @param {Array} nums - The input array.
* @return {Array} The modified input array.
*/
const moveZeros = (nums) => {
let left = 0
let right = 0
while (right < nums.length) {
// If the current element is not zero,
// swap it with the element at the 'left' index
if (nums[right] !== 0) {
// destructuring assignment with swap.
// Doing this way avoids allocation three variables
[nums[left], nums[right]] = [nums[right],nums[left]]
left++;
}
right++;
}
return nums
}
console.log( moveZeros([0,1,2,3]) )
console.log( moveZeros([1,2,0,3,4]) )
console.log( moveZeros([1,2,3,4,0]) )
console.log( moveZeros([1,0,0,4]) )
console.log( moveZeros([0,2,3,0]) )
console.log( moveZeros([0]) )
console.log( moveZeros([1]) )
console.log( moveZeros([]) )
/**
* [ 1, 2, 3, 0 ]
* [ 1, 2, 3, 4, 0 ]
* [ 1, 2, 3, 4, 0 ]
* [ 1, 4, 0, 0 ]
* [ 2, 3, 0, 0 ]
* [ 0 ]
* [ 1 ]
* []
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment