Skip to content

Instantly share code, notes, and snippets.

@danielnass
Created August 3, 2022 18:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielnass/5d6bd3ce3f11dabcf4891b4ea0a6bf51 to your computer and use it in GitHub Desktop.
Save danielnass/5d6bd3ce3f11dabcf4891b4ea0a6bf51 to your computer and use it in GitHub Desktop.
JavaScript - Move zeroes to end of the array
const arr = [0,1,0,2,0,3,0,4,0,5];
const arrZeroesFiltered = arr.filter((cv) => cv !== 0);
/*
* or if you know your arr will return just numbers
* and not things like null or undefined
* const arrZeroesFiltered = arr.filter(Boolean);
*/
const zeroes = arr.length - arrZeroesFiltered.length;
[...arrZeroesFiltered, ...Array(zeroes).fill(0)];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment