To remove null, undefined, and empty elements from a JavaScript array without mutating the original array, use Array.prototype.filter() with an explicit predicate that rejects null, undefined, empty or whitespace-only strings ("" / " "), and empty array slots (sparse holes). Avoid .filter(Boolean) when your data can legitimately contain falsy values such as 0 or false.
1. Filtering null, undefined, Empty Strings, and Sparse Holes Safely
Use a non-mutating .filter() helper that checks index existence (Object.prototype.hasOwnProperty.call(arr, index) or iterating cleanly) and explicitly excludes null, undefined, and empty/whitespace strings while preserving 0, false, and NaN when intended:
// Remove null, undefined, empty/whitespace strings, and sparse holes without mutating input
function compactArray(items, { trimStrings = true } = {}) {
if (!Array.isArray(items)) {
return [];
}
const result = [];
for (let i = 0; i < items.length; i += 1) {
if (!Object.prototype.hasOwnProperty.call(items, i)) {
continue;
}
const value = items[i];
if (value === null || value === undefined) {
continue;
}
if (typeof value === "string") {
const candidate = trimStrings ? value.trim() : value;
if (candidate.length === 0) {
continue;
}
}
result.push(value);
}
return result;
}
// Example usage:
const rawItems = ["js", "", " ", null, undefined, 0, false, "node"];
console.log(compactArray(rawItems)); // ["js", 0, false, "node"]
- Preserves
0andfalse: Unlike.filter(Boolean), numeric zero and booleanfalseare kept as valid values. - Handles sparse arrays: Skips empty slots (
[1, , 3]) and returns a brand-new dense array without mutatingitems.
2. Removing Nested Empty Values or Empty Containers
When an array contains nested arrays or objects (such as empty sub-arrays [] or blank records), normalize or filter inner items explicitly before keeping or dropping elements:
// Remove null, undefined, and empty strings while cleaning nested arrays non-mutatingly
function compactNestedArray(items, { dropEmptyArrays = true } = {}) {
if (!Array.isArray(items)) {
return [];
}
return items.reduce((acc, item) => {
if (item === null || item === undefined) {
return acc;
}
if (typeof item === "string" && item.trim() === "") {
return acc;
}
if (Array.isArray(item)) {
const cleanedInner = compactNestedArray(item, { dropEmptyArrays });
if (!dropEmptyArrays || cleanedInner.length > 0) {
acc.push(cleanedInner);
}
return acc;
}
acc.push(item);
return acc;
}, []);
}
// Example usage:
console.log(compactNestedArray(["a", ["", null, "b"], [], undefined])); // ["a", ["b"]]
- Non-mutating recursion: Uses
.reduce()to build new arrays at every level without altering input arrays. - Configurable empty sub-arrays: Lets you decide whether nested arrays that become empty should be dropped or retained as
[].
3. Common Traps to Avoid
Cleaning empty and nullish values from JavaScript arrays often hits a few pitfalls:
- Using
.filter(Boolean)blindly:.filter(Boolean)strips0,0n,false, andNaNalongsidenull,undefined, and""—which can corrupt counts, flags, or numeric series. - Forgetting whitespace-only strings (
" "): Form inputs or CSV columns often contain spaces; checkvalue.trim() === ""when blank text counts as empty. - Mutating arrays with
splice()inside a forwardforloop: Removing elements in-place shifts indices and skips items—always return a new filtered array instead.
TL;DR: Filter arrays non-mutatingly with explicit checks for null, undefined, empty/whitespace strings, and sparse slots rather than .filter(Boolean) so valid falsy values like 0 and false are preserved.
