Skip to content

Instantly share code, notes, and snippets.

@jkumara
Created August 31, 2023 08:46
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jkumara/d440aa3d3a1c6316eb9909e8c66bb941 to your computer and use it in GitHub Desktop.
Save jkumara/d440aa3d3a1c6316eb9909e8c66bb941 to your computer and use it in GitHub Desktop.
Move all zeros of the array to the end while maintaining the relative order of all non-zeros.
/**
* Given an array of integers, move all zeros of the array to the end while
* maintaining the relative order of all non-zeros.
*
* Example:
*
* $ move0([1,3,0,111,57,0,5,0,9])
* $ [1,3,111,57,5,9,0,0,0]
*/
const move0 = (arr) =>
arr.reduceRight((acc, cur) => (acc[cur ? "unshift" : "push"](cur), acc), []);
console.log(move0([1, 3, 0, 111, 57, 0, 5, 0, 9])); // [1,3,111,57,5,9,0,0,0]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment