A proposal to create a more compact array, by discarding falsey values
const array = [0, 1, false, 2, '', 3]
array.compact()
// => [1, 2 3]- Keith Cirkel (@keithamus)
Current Stage: 0
Compacting an Array to only truthy values is a common operation. It's
usually handled by calling filter with an identity function
(44k results):
array.filter(i => i)or by passing the Boolean value as a predicate function (133K results):
array.filter(Boolean)or a simple function returning the Boolean value of just the first parameter (1K results):
array.filter(i => Boolean(i))or even a simple function returning the doubly-negated value of just the first parameter (18K results):
array.filter(i => !!i)All of these can be somewhat tricky to reason about, and the various styles can be used in the same codebase to make matters more confusing.
Lodash includes _.compact() which as a standalone
dependency receives ~400,000 downloads per week.
Sugar includes .compact(all) which may cause
webcompat issues - as the all boolean (defaulting to false)
determines if elements removed should be falsey (when true)
or nullish (when false).
- Ruby has a
.compactmethod, which wil return an Array with allnilelements removed
- None as of yet.