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:
""0falsenullundefinedNaN
This is shorter, but it is only correct if you want to remove all falsy values, not just empty strings.
Removing blank strings including spaces
Sometimes an item is not exactly empty, but contains only spaces:
const cities = ["Kathmandu", " ", "Pokhara", "", "Dharan"];
const cleanedCities = cities.filter(city => city.trim() !== "");
console.log(cleanedCities);
// ["Kathmandu", "Pokhara", "Dharan"]
trim() removes whitespace from the beginning and end of a string before checking if it is empty.
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.
Final result:
["Kathmandu", "Pokhara", "Dharan"]
Important detail
The original array is not changed unless you assign the result back:
let cities = ["Kathmandu", "Pokhara", "", "Dharan"];
cities = cities.filter(city => city !== "");
Now cities refers to the cleaned 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 !== "");
Search keywords
If users type comma-separated values, splitting the string can create blanks:
const input = "apple,banana,,orange";
const keywords = input.split(",").filter(word => word !== "");
console.log(keywords);
// ["apple", "banana", "orange"]
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() !== "");
This is useful when data is unreliable.
Pattern: reusable helper function
function removeEmptyStrings(arr) {
return arr.filter(item => item !== "");
}
In larger codebases, small helper functions improve readability.
Pattern: validation before saving
Before storing data in a database or sending it to an API, developers often clean arrays first to avoid invalid records.
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", "", "Pokhara"];
cities.filter(city => city !== "");
console.log(cities);
// Still contains the empty string
Correct:
cities = cities.filter(city => city !== "");
3. Not handling whitespace-only strings
Broken cleanup:
const cities = ["Kathmandu", " ", "Pokhara"];
const cleaned = cities.filter(city => city !== "");
console.log(cleaned);
// ["Kathmandu", " ", "Pokhara"]
Correct:
const cleaned = cities.filter(city => city.trim() !== "");
4. Assuming JavaScript has a built-in compact() method
JavaScript arrays do not have a native compact() method.
Use filter() instead:
const cleaned = cities.filter(city => city !== "");
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 | cities.filter(city => city.trim() !== "") |
filter() vs manual loop
| Method | Pros | Cons |
|---|---|---|
filter() | Short, readable, expressive, common in modern JavaScript | Creates a new array |
for loop | Flexible, familiar, can do many operations | More verbose for simple filtering |
If your goal is simply to remove items based on a condition, filter() is usually the clearest choice.
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
arr.filter(item => item !== "")
Safe choice for user-entered strings
arr.filter(item => typeof item === "string" && item.trim() !== "")
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 => item.trim() !== "");
Can I use this with values from split()?
Yes. This is very common:
const items = text.split(",").filter(item => 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
Add a Default Value to an Existing Column in a Rails Migration
Learn how to add or change a default value on an existing database column using Rails Active Record migrations safely.
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.