Skip to content

Instantly share code, notes, and snippets.

@obonyojimmy
Created April 23, 2018 20:09
Show Gist options
  • Save obonyojimmy/1903a0959cfabb1277f99231d60d48b8 to your computer and use it in GitHub Desktop.
Save obonyojimmy/1903a0959cfabb1277f99231d60d48b8 to your computer and use it in GitHub Desktop.
remove-empty-elements-from-an-array-in-javascript
// https://stackoverflow.com/a/48163228/1226748
// For removing holes, you should use
arr.filter(() => true)
// For removing hole, and, falsy (null, undefined, 0, -0, NaN, "", false, document.all) values:
arr.filter(x => x)
// For removing hole, null, and, undefined:
arr.filter(x => x != null)
arr = [, null, (void 0), 0, -0, NaN, false, '', 42];
console.log(arr.filter(() => true)); // [null, (void 0), 0, -0, NaN, false, '', 42]
console.log(arr.filter(x => x)); // [42]
console.log(arr.filter(x => x != null)); // [0, -0, NaN, false, "", 42]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment