proposal-array-compact
A proposal to create a more compact array, by discarding falsey values
const array = [0, 1, false, 2, '', 3]
array.compact()
// => [1, 2 3]
Champions
- Keith Cirkel (@keithamus)
Status
Current Stage: 0
Motivation
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:
array.filter(Boolean)
Both of these can be somewhat tricky to reason about, and both 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
).
Other languages
- Ruby has a
.compact
method, which wil return an Array with allnil
elements removed
Polyfill
- None as of yet.