Question
I have the following JavaScript array:
let Copycities = ["Kathmandu", "Pokhara", "", "Dharan", "Butwal"];
I want to remove the blank element so that the result becomes:
let Copycities = ["Kathmandu", "Pokhara", "Dharan", "Butwal"];
Is there a built-in method similar to compact that can do this without writing a manual loop?
Short Answer
By the end of this page, you will understand how to remove empty string values from a JavaScript array, when to use filter(), how truthy and falsy values affect the result, and which approach is safest in real code.
Concept
In JavaScript, the most common way to remove unwanted items from an array is to use the filter() method.
filter() creates a new array containing only the elements that pass a condition. This is useful when you want to remove:
- empty strings
nullundefined- invalid values
- items that do not match a rule
For your case, the unwanted value is an empty string:
""
So you can tell filter() to keep only the items that are not empty strings.
const cities = ["Kathmandu", "Pokhara", "", "Dharan", "Butwal"];
const result = cities.filter(city => city !== "");
This matters because array cleanup is very common in real programming. Data often comes from:
- forms
- APIs
- CSV files
- user input
- configuration files
In all of these cases, arrays may contain blank or invalid values. Knowing how to clean arrays safely is a core JavaScript skill.
Mental Model
Think of filter() like a security gate.
Each array item walks up to the gate one by one.
- If the item passes the rule, it is allowed through.
- If it fails the rule, it is removed.
For example, with this rule:
city => city !== ""
"Kathmandu"passes"Pokhara"passes""fails"Dharan"passes"Butwal"passes
So only the non-empty city names get through the gate.
Syntax and Examples
The basic syntax of filter() is:
const newArray = array.filter((item) => {
return condition;
});
For removing empty strings:
const cities = ["Kathmandu", "Pokhara", "", "Dharan", "Butwal"];
const cleanedCities = cities.filter(city => city !== "");
console.log(cleanedCities);
// ["Kathmandu", "Pokhara", "Dharan", "Butwal"]
Short version using truthy values
You may also see this:
const cleanedCities = cities.filter(Boolean);
This removes all falsy values, such as:
""0false
Step by Step Execution
Consider this example:
const cities = ["Kathmandu", "Pokhara", "", "Dharan"];
const cleanedCities = cities.filter(city => city !== "");
Here is what happens step by step:
filter()starts with an empty result array.- It checks the first item:
"Kathmandu"- Is
"Kathmandu" !== ""? Yes. - Keep it.
- Is
- It checks the second item:
"Pokhara"- Is
"Pokhara" !== ""? Yes. - Keep it.
- Is
- It checks the third item:
""- Is
"" !== ""? No. - Remove it.
- Is
- It checks the fourth item:
"Dharan"- Is
"Dharan" !== ""? Yes. - Keep it.
- Is
filter()returns a new array.
Real World Use Cases
Removing blank values from arrays is useful in many practical situations:
Form input cleanup
A user may submit a list of tags or city names with some blank entries:
const tags = ["news", "", "sports", ""];
const validTags = tags.filter(tag => tag !== "");
CSV or file processing
Imported file data may contain empty cells:
const row = ["Alice", "", "Developer", "Kathmandu"];
const cleanedRow = row.filter(value => value !== "");
API response cleanup
Some APIs may return incomplete arrays:
const categories = ["Books", "", "Electronics"];
const cleanedCategories = categories.filter(c => c !== );
Real Codebase Usage
In real projects, developers usually do more than just remove empty strings. They often combine filter() with validation and normalization.
Pattern: assign cleaned data immediately
const cleanedCities = cities.filter(city => city !== "");
This keeps the original data untouched and makes the intent clear.
Pattern: trim before filtering
const cleanedCities = cities
.map(city => city.trim())
.filter(city => city !== "");
This is common when data comes from users.
Pattern: guard against non-strings
const values = ["Kathmandu", null, "", "Pokhara"];
const cleaned = values.filter(value => typeof value === "string" && value.trim() !== );
Common Mistakes
1. Using filter(Boolean) when 0 or false should stay
Broken for some cases:
const values = ["Kathmandu", "", 0, false, "Pokhara"];
const cleaned = values.filter(Boolean);
console.log(cleaned);
// ["Kathmandu", "Pokhara"]
This removed 0 and false too.
Use this instead if you only want to remove empty strings:
const cleaned = values.filter(value => value !== "");
2. Forgetting that filter() returns a new array
Broken expectation:
let cities = ["Kathmandu", , ];
cities.( city !== );
.(cities);
Comparisons
| Approach | What it removes | Best when | Example |
|---|---|---|---|
array.filter(item => item !== "") | Only empty strings | You want precise control | cities.filter(city => city !== "") |
array.filter(Boolean) | All falsy values | You want to remove "", null, undefined, 0, false, NaN | values.filter(Boolean) |
array.filter(item => item.trim() !== "") | Empty and whitespace-only strings | User input may contain spaces |
Cheat Sheet
Remove only empty strings
const cleaned = arr.filter(item => item !== "");
Remove empty and whitespace-only strings
const cleaned = arr.filter(item => item.trim() !== "");
Remove all falsy values
const cleaned = arr.filter(Boolean);
filter() rule
true-> keep the itemfalse-> remove the item
Important facts
filter()returns a new array- it does not change the original array unless reassigned
- JavaScript has no native
compact()method for arrays
Safe choice for this question
FAQ
How do I remove empty strings from an array in JavaScript?
Use filter():
const cleaned = arr.filter(item => item !== "");
Is there a JavaScript method like compact()?
Not in native JavaScript arrays. The usual replacement is filter().
Does filter() change the original array?
No. It returns a new array. Assign the result back if needed.
What is the difference between filter(Boolean) and filter(item => item !== "")?
filter(Boolean) removes all falsy values. filter(item => item !== "") removes only empty strings.
How do I remove strings that contain only spaces?
Use trim() before checking:
const cleaned = arr.filter( => item.() !== );
Mini Project
Description
Build a small JavaScript utility that cleans a list of user-entered city names. The list may contain empty strings or strings made only of spaces. This demonstrates how filter() and trim() are used together in practical input cleanup.
Goal
Create a function that returns a clean array of city names with blank entries removed.
Requirements
- Create an array containing valid city names, empty strings, and whitespace-only strings.
- Write a function that removes invalid entries.
- Keep only non-empty city names after trimming whitespace.
- Print both the original array and the cleaned array.
Keep learning
Related questions
Calling a Class Method from an Instance in Ruby
Learn how to call a class method from an instance in Ruby using self.class, with examples, pitfalls, and practical usage patterns.
Calling an Overridden Monkey-Patched Method in Ruby
Learn how to call the original method when monkey patching in Ruby, including alias_method patterns, examples, pitfalls, and practical usage.
Convert a Unix Timestamp to Ruby DateTime
Learn how to convert Unix timestamps to Ruby DateTime and Time objects, with examples, differences, pitfalls, and practical Ruby usage.