Created
August 31, 2023 08:46
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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