keithamus/proposal-array-compact

A proposal for adding a `compact()` method to Arrays

★ 6Forks 1HTMLGitHub ↗Compare

README

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

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 (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).

Other languages

Polyfill

  • None as of yet.

Contributors

keithamusJamesMGreeneljharb

Issues