Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to remove blank (undefined) elements from JavaScript array - JavaScript
When working with JavaScript arrays, you may encounter sparse arrays containing empty slots (undefined elements). These gaps can occur when elements are deleted or when arrays are created with missing values.
const arr = [4, 6, , 45, 3, 345, , 56, 6];
console.log(arr);
console.log("Length:", arr.length);
[ 4, 6, <1 empty item>, 45, 3, 345, <1 empty item>, 56, 6 ] Length: 9
We need to remove only the undefined and empty values, not all falsy values like 0, false, or empty strings.
Method 1: Using splice() with for loop
Use a for loop to iterate over the array and Array.prototype.splice() to remove undefined elements in place:
const arr = [4, 6, , 45, 3, 345, , 56, 6];
const eliminateUndefined = arr => {
for(let i = 0; i < arr.length; ){
if(typeof arr[i] !== 'undefined'){
i++;
continue;
};
arr.splice(i, 1);
};
};
eliminateUndefined(arr);
console.log(arr);
[
4, 6, 45, 3,
345, 56, 6
]
Method 2: Using filter() (Creates New Array)
A cleaner approach using filter() that creates a new array without undefined elements:
const arr = [4, 6, , 45, 3, 345, , 56, 6];
const cleanArray = arr.filter((element, index) => index in arr);
console.log(cleanArray);
console.log("Original array:", arr);
[ 4, 6, 45, 3, 345, 56, 6 ] Original array: [ 4, 6, <1 empty item>, 45, 3, 345, <1 empty item>, 56, 6 ]
Method 3: Using Array.from() with Filtering
const arr = [4, 6, , 45, 3, 345, , 56, 6]; const cleanArray = Array.from(arr.filter(() => true)); console.log(cleanArray);
[ 4, 6, 45, 3, 345, 56, 6 ]
Comparison
| Method | Modifies Original? | Performance | Readability |
|---|---|---|---|
| splice() loop | Yes | Good | Medium |
| filter() | No | Good | High |
| Array.from() | No | Good | High |
Key Points
? Empty array slots are different from undefined values ? The splice() method modifies the original array in place ? Filter-based approaches create new arrays, preserving the original ? Use `index in arr` to check for actual array holes
Conclusion
Use filter() for cleaner code when you can create a new array, or the splice() approach when you must modify the original array in place. Both methods effectively remove undefined elements while preserving other falsy values.
