Lodash _.compact() method
What you’ll learn
- What
_.compact(array)removes and what it keeps. - How it compares to
array.filter(Boolean)for everyday cleanup. - How to import
compactwithout loading all of Lodash. - Open each numbered example in the Try it editor (
?tryit=1,2,3) with Lodash from a CDN. - Edge cases such as
NaN, sparse slots, and non-primitive “empty” values.
Prerequisites
Know JavaScript truthiness and arrays; optional prior read of _.chunk() on this site.
- You understand which values are falsy in JavaScript (
0,"",NaN,null,undefined,false). - You can run snippets in Node or use the Try-it editor in a modern browser.
Overview
_.compact returns a new array containing only the truthy elements of the input. It is a concise way to strip placeholder falsy values before validation, rendering, or persistence.
Non-destructive
The input array is unchanged; you work with a new dense list of truthy items.
Falsy cleanup
Removes the six falsy primitives you see most often in API and form payloads.
Pairs with chunk
Often used after mapping or joining steps that insert null or undefined placeholders.
Syntax
_.compact(array) - array: the collection to clean (array-like values are coerced).
- Returns: a new array with only truthy values, preserving relative order.
Mixed truthy and falsy
Falsy entries disappear; numbers and non-empty strings remain in order.
import compact from "lodash/compact";
const cleaned = compact([0, 1, false, 2, "", 3]);
// [1, 2, 3] All falsy
When every element is falsy, the result is an empty array.
import compact from "lodash/compact";
compact([false, null, 0, "", undefined, NaN]);
// [] Already dense
If there are no falsy values, you get a shallow copy of the same sequence.
import compact from "lodash/compact";
compact([1, 2, 3]);
// [1, 2, 3] 📋 _.compact vs filter(Boolean)
| Topic | _.compact | .filter(Boolean) |
|---|---|---|
| Intent | Name signals “drop falsy placeholders” | Generic filter with coercion to boolean |
| Typical primitives | Same removals for 0, "", NaN, etc. | Same for most day-to-day arrays |
| Dependency | One Lodash import | No dependency |
Pitfalls to avoid
Removing meaningful 0
Scores, counts, and IDs can be zero. If 0 is valid data, do not compact that array without mapping first.
{} stays
Empty objects are truthy. Use a different helper if you need to drop “empty” object records.
Holes
Prefer dense arrays; sparse behavior can surprise readers. Build lists with push or filter explicitly when holes matter.
❓ FAQ
Summary
- Purpose:
_.compact(array)keeps truthy elements in a new array. - Safety: never mutates the source array.
- Next: Lodash _.concat(), _.chunk(), or the array methods hub.
_.compact removes false, null, 0, "", undefined, and NaN. It does not remove other values you might consider “empty” such as empty objects {}.
6 people found this page helpful
