Logo

How to remove empty elements from an array in JavaScript?

Removing empty elements from an array in JavaScript is a common requirement—especially when dealing with user inputs, CSV data, or any scenario where you might have sparse arrays (i.e., arrays with “holes”) or elements that are empty strings, null, or undefined. Below are the most popular strategies for cleaning up your data, along with practical insights and performance considerations.

1. Using filter() with a Custom Condition

The filter() method is ideal for building your own logic:

const array = ["apple", "", "banana", undefined, "cherry", null, ""]; const cleanedArray = array.filter((element) => { // Define what “empty” means for your specific case return element !== "" && element !== undefined && element !== null; }); console.log(cleanedArray); // Possible Output: ["apple", "banana", "cherry"]
  • Explanation: Here we skip any value that is "" (empty string), undefined, or null. Feel free to tweak this condition to fit your use case (e.g., keep empty strings but remove undefined).

2. Using filter(Boolean) for Falsy Values

If you want to remove all falsy values (i.e., 0, "", null, undefined, NaN, false), you can rely on JavaScript’s type coercion:

const array = ["apple", "", "banana", undefined, "cherry", null, 0]; const cleanedArray = array.filter(Boolean); console.log(cleanedArray); // Output: ["apple", "banana", "cherry"]
  • Note: This also removes 0 and false. Make sure that’s the desired behavior.

3. Removing “Holes” in Sparse Arrays

Arrays can have “empty slots” (e.g., created by new Array(5) or explicitly leaving out elements). To remove these holes while keeping other values (including 0 and empty strings):

const sparseArray = [1, , 2, 3, , 4, 0]; const denseArray = sparseArray.filter(() => true); console.log(denseArray); // Output: [1, 2, 3, 4, 0]
  • Explanation: Passing a callback that always returns true effectively copies only the filled elements, removing any holes.

4. In-Place Removal with splice()

If you prefer an in-place approach (modifying the original array), you can iterate from the end to avoid index shifting:

const array = ["apple", "", "banana", null, "cherry"]; for (let i = array.length - 1; i >= 0; i--) { if (array[i] === "" || array[i] === null) { array.splice(i, 1); } } console.log(array); // Output: ["apple", "banana", "cherry"]
  • Note: Repeatedly calling splice() can be O(n²) in worst-case scenarios because each splice can trigger index shifts. For large arrays, consider filter() for an O(n) solution.

Performance & Interview Considerations

  1. Time Complexity:
    • filter() runs in O(n) time—preferred for large arrays.
    • Repeated splice() calls can degrade to O(n²).
  2. Definition of “Empty”:
    • Does “empty” mean an empty string? null? undefined? A “hole” in a sparse array? Clarify your criteria.
  3. Maintain or Create a New Array:
    • filter() creates a new array (non-mutating), perfect for functional programming or frameworks like React.
    • Using splice() modifies the original array, which might be necessary if other parts of your code share that reference.

Level Up Your Coding Skills

If you’re preparing for interviews or want a deeper understanding of JavaScript, here are a few resources from DesignGurus.io to consider:

You can also practice your skills and receive personalized feedback from ex-FAANG engineers with a Coding Mock Interview. And don’t forget to visit the DesignGurus YouTube Channel for free, in-depth videos on coding and system design.

Key Takeaways

  • filter() is your best friend for a clean, O(n) solution that leaves the original array intact.
  • Decide how you define “empty” before writing your condition.
  • Consider your performance and data-structure needs (in-place vs. returning a new array).

By choosing the right approach and carefully defining “empty,” you’ll ensure your JavaScript arrays stay clean and bug-free, whether you’re building a production app or acing your next coding interview. Happy coding!

CONTRIBUTOR
TechGrind