Remove '0','undefined' and empty values from an array in JavaScript

To remove '0', 'undefined' and empty values from an array in JavaScript, you can use several methods. The most common approaches are using splice() with a loop or the filter() method.

Method 1: Using splice() with for loop

This method modifies the original array by removing falsy values in place:

var allValues = [10, false, 100, 150, '', undefined, 450, null, 0];
console.log("Original Array:");
console.log(allValues);

for (var index = 0; index < allValues.length; index++) {
    if (!allValues[index]) {
        allValues.splice(index, 1);
        index--; // Adjust index after removal
    }
}

console.log("After removing falsy values:");
console.log(allValues);
Original Array:
[ 10, false, 100, 150, '', undefined, 450, null, 0 ]
After removing falsy values:
[ 10, 100, 150, 450 ]

Method 2: Using filter() (Recommended)

The filter() method creates a new array with only truthy values, leaving the original unchanged:

var allValues = [10, false, 100, 150, '', undefined, 450, null, 0];
console.log("Original Array:");
console.log(allValues);

var filteredArray = allValues.filter(Boolean);
console.log("Filtered Array:");
console.log(filteredArray);
console.log("Original Array remains unchanged:");
console.log(allValues);
Original Array:
[ 10, false, 100, 150, '', undefined, 450, null, 0 ]
Filtered Array:
[ 10, 100, 150, 450 ]
Original Array remains unchanged:
[ 10, false, 100, 150, '', undefined, 450, null, 0 ]

Method 3: Custom filter with explicit checks

For more control over which values to remove, you can use a custom filter function:

var allValues = [10, false, 100, 150, '', undefined, 450, null, 0];

var cleanArray = allValues.filter(function(value) {
    return value !== null && 
           value !== undefined && 
           value !== '' && 
           value !== 0 && 
           value !== false;
});

console.log("Original Array:");
console.log(allValues);
console.log("Clean Array:");
console.log(cleanArray);
Original Array:
[ 10, false, 100, 150, '', undefined, 450, null, 0 ]
Clean Array:
[ 10, 100, 150, 450 ]

Comparison

Method Modifies Original Performance Readability
splice() with loop Yes Slower More complex
filter(Boolean) No Faster Clean & concise
Custom filter No Faster More explicit

Falsy Values in JavaScript

The following values are considered falsy and will be removed:

  • false
  • 0
  • '' (empty string)
  • null
  • undefined
  • NaN

Conclusion

Use filter(Boolean) for clean, readable code that preserves the original array. Use splice() only when you need to modify the original array in place.

Updated on: 2026-03-15T23:18:59+05:30

308 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements