Lodash _.compact Behavior with Sparse Arrays
The Lodash _.compact method removes all falsey values
from an array, which directly affects how it handles sparse arrays
containing missing index slots (holes). When _.compact
encounters an array with unassigned or missing indices, it evaluates
those slots as undefined. Because undefined is
a falsey value in JavaScript, the method omits the missing slots
entirely, returning a newly packed, dense array containing only truthy
values.
How Sparse Arrays Work in JavaScript
A sparse array is an array where certain indices have not been assigned a value, creating empty slots. For example:
const sparseArray = [1, , 3]; // Index 1 is an empty slot
console.log(sparseArray.length); // 3
console.log(sparseArray[1]); // undefinedAlthough the slot at index 1 is not explicitly defined with a value,
attempting to read its property returns undefined.
How _.compact
Processes Missing Slots
Lodash implements _.compact by iterating over the input
array using its total length, checking each index from 0 to
length - 1:
const _ = require('lodash');
const input = ['apple', , 'banana', undefined, 0, 'cherry'];
const result = _.compact(input);
console.log(result);
// Output: ['apple', 'banana', 'cherry']During execution, _.compact evaluates each item:
- It accesses the element at each index via standard indexed lookup
(
array[index]). - When accessing a missing slot, the operation returns
undefined. - The method evaluates the truthiness of the value. Since
undefinedcoerces tofalse, the slot is excluded from the new array. - Valid, truthy elements are pushed into a new, dense array.
Comparison with
Native Array.prototype.filter
Native JavaScript array methods such as forEach,
map, and filter typically skip empty slots
without invoking the callback. For instance, using
sparseArray.filter(Boolean) also removes empty slots, but
it does so because native iterations bypass unassigned indices
entirely.
Lodash's _.compact reaches the same end result—a dense
array with no holes—because it reads the missing indices directly as
undefined and filters them out alongside other falsey
values like false, null, 0,
"", and NaN.