To remove empty elements from an array in JavaScript, the approach depends on how you define “empty.” Below are common scenarios and their solutions:
1. Remove Empty Strings (""
)
If “empty” means strings with no characters:
const arr = ["apple", "", "banana", ""];
const filtered = arr.filter(element => element !== "");
// Result: ["apple", "banana"]
2. Remove Falsy Values
If “empty” includes all falsy values (""
, 0
, false
, null
, undefined
, NaN
):
const arr = ["", 0, false, null, undefined, NaN, "text"];
const filtered = arr.filter(Boolean);
// Result: ["text"]
3. Remove Whitespace-Only Strings
If “empty” includes strings with only whitespace (e.g., " "
, "\t"
, "\n"
):
const arr = ["a", " ", "\t", "b"];
const filtered = arr.filter(element => element.trim() !== "");
// Result: ["a", "b"]
4. Remove Sparse Elements (Array Holes)
If “empty” means uninitialized array elements (e.g., [1, , 3]
):
const arr = [1, , 3]; // Sparse array with a hole
const filtered = arr.filter(() => true);
// Result: [1, 3] (holes removed)
5. Remove null
or undefined
If “empty” specifically means null
or undefined
:
const arr = ["a", null, "b", undefined];
const filtered = arr.filter(element => element != null);
// Result: ["a", "b"]
Key Notes
- Immutable Operation:
filter
returns a new array and does not modify the original. - Edge Cases: Adjust the logic based on your definition of “empty” (e.g.,
0
orfalse
might be valid data). - Performance: These methods are efficient for most use cases.
Example Workflow
// Original array with mixed "empty" elements
const arr = ["hello", "", " ", null, 0, false, undefined, "world"];
// Remove all falsy values and whitespace-only strings
const cleaned = arr.filter(element => {
return typeof element === "string"
? element.trim() !== ""
: Boolean(element);
});
console.log(cleaned); // ["hello", "world"]
Choose the method that aligns with your definition of “empty” elements!