JavaScript
Programming
Array Manipulation
Coding Tips
Web Development

Remove empty elements from an array in Javascript

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

JavaScript arrays can contain "empty" elements — null, undefined, empty strings "", 0, false, NaN, or sparse array holes. The method you choose depends on which values you consider "empty." filter(Boolean) removes all falsy values, filter(x => x !== undefined) targets specific types, and flat() removes sparse holes. Understanding falsy values in JavaScript is key to choosing the right approach.

Remove All Falsy Values with filter(Boolean)

javascript
1const arr = [1, null, "", 0, undefined, 2, false, 3, NaN];
2const cleaned = arr.filter(Boolean);
3
4console.log(cleaned);  // [1, 2, 3]

Boolean is a constructor function that returns false for falsy values and true for truthy values. Passing it to filter removes all falsy elements:

ValueBoolean(value)Removed?
nullfalseYes
undefinedfalseYes
""falseYes
0falseYes
falsefalseYes
NaNfalseYes
"hello"trueNo
42trueNo
[]trueNo
{}trueNo

Remove Only null and undefined

javascript
1const arr = [1, null, 0, undefined, "", 2, false, 3];
2
3// Keep 0, "", and false — only remove null and undefined
4const cleaned = arr.filter(x => x != null);
5
6console.log(cleaned);  // [1, 0, "", 2, false, 3]

The loose equality x != null checks for both null and undefined (they are loosely equal to each other) while keeping other falsy values like 0, "", and false.

Remove Only Empty Strings

javascript
1const arr = ["hello", "", "world", "", "test"];
2
3const cleaned = arr.filter(x => x !== "");
4console.log(cleaned);  // ["hello", "world", "test"]
5
6// Or trim whitespace-only strings too
7const arr2 = ["hello", "", "  ", "world", "\t"];
8const cleaned2 = arr2.filter(x => x.trim() !== "");
9console.log(cleaned2);  // ["hello", "world"]

Remove Sparse Array Holes

JavaScript arrays can have "holes" — indices with no value at all (different from undefined):

javascript
1const sparse = [1, , , 4, , 6];  // Holes at indices 1, 2, 4
2console.log(sparse.length);       // 6
3
4// filter skips holes automatically
5const cleaned = sparse.filter(() => true);
6console.log(cleaned);  // [1, 4, 6]
7
8// flat() also removes holes
9const cleaned2 = sparse.flat();
10console.log(cleaned2);  // [1, 4, 6]
11
12// Array.from copies holes as undefined
13const withUndefined = Array.from(sparse);
14console.log(withUndefined);  // [1, undefined, undefined, 4, undefined, 6]

Using reduce for Custom Filtering

javascript
1const arr = [1, null, "", 0, undefined, 2, false, 3];
2
3// Keep everything except null, undefined, and empty strings
4const cleaned = arr.reduce((acc, val) => {
5    if (val !== null && val !== undefined && val !== "") {
6        acc.push(val);
7    }
8    return acc;
9}, []);
10
11console.log(cleaned);  // [1, 0, 2, false, 3]

Removing Empty Values from Arrays of Objects

javascript
1const users = [
2    { name: "Alice", email: "[email protected]" },
3    null,
4    { name: "Bob", email: "" },
5    undefined,
6    { name: "", email: "[email protected]" },
7];
8
9// Remove null/undefined entries
10const validUsers = users.filter(Boolean);
11console.log(validUsers.length);  // 3
12
13// Remove entries where name is empty
14const namedUsers = users.filter(u => u && u.name);
15console.log(namedUsers);
16// [{ name: "Alice", email: "[email protected]" }, { name: "Bob", email: "" }]

In-Place Modification

All previous examples create new arrays. To modify in place, iterate backwards:

javascript
1const arr = [1, null, 2, undefined, 3, ""];
2
3for (let i = arr.length - 1; i >= 0; i--) {
4    if (!arr[i] && arr[i] !== 0) {
5        arr.splice(i, 1);
6    }
7}
8
9console.log(arr);  // [1, 2, 3, 0]  — kept 0

Iterating backwards prevents index shifting from affecting unprocessed elements.

Chaining with map

A common pattern — map values and then filter out the empty results:

javascript
1const rawData = ["42", "", "hello", "0", null, "  "];
2
3const numbers = rawData
4    .filter(x => x != null && x.trim() !== "")  // Remove empty
5    .map(Number)                                   // Convert to number
6    .filter(x => !isNaN(x));                      // Remove NaN
7
8console.log(numbers);  // [42, 0]

Common Pitfalls

  • filter(Boolean) removes 0 and false: If your array legitimately contains 0 or false, filter(Boolean) strips them out. Use filter(x => x != null) to keep falsy values that are not null/undefined.
  • Confusing sparse holes with undefined: A sparse array hole ([1, , 3]) is not the same as undefined. filter, map, and forEach skip holes entirely, but Array.from converts them to undefined. The behavior differs by method.
  • Forgetting that filter returns a new array: arr.filter(Boolean) does not modify arr. If you need to update the original, assign the result back: arr = arr.filter(Boolean) or use splice for in-place modification.
  • Using == instead of === for empty string checks: 0 == "" is true in JavaScript due to type coercion. Use strict equality (===) when checking for specific empty values to avoid accidentally removing numbers.
  • Not handling whitespace strings: " " (spaces, tabs, newlines) is truthy and passes filter(Boolean). If whitespace-only strings should be treated as empty, use x.trim() !== "" or x.trim().length > 0.

Summary

  • filter(Boolean) removes all falsy values (null, undefined, 0, "", false, NaN)
  • filter(x => x != null) removes only null and undefined, keeping 0, "", and false
  • filter(x => x !== "") targets empty strings specifically
  • Sparse array holes are skipped by filter, map, and forEach automatically
  • Use strict equality (===) to avoid type coercion surprises
  • filter creates a new array — use splice with backward iteration for in-place modification

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.