How to Remove Empty Elements from an Array in JavaScript
Topic: JavaScript / jQueryPrev|Next
Answer: Use the filter()
Method
You can simply use the filter()
method to remove empty elements (or falsy values) from a JavaScript array. A falsy value is a value that is considered false in a Boolean context.
Falsy values in JavaScript includes an empty string ""
, false
, 0
, null
, undefined
, and NaN
.
Let's check out the following example to understand how it basically works:
Example
Try this code »// Sample array
var arr = [1,2,,3,,-4,"",null,,0,,false,undefined,5,,-5,6,"",7,,];
// Performing filtration
var filtered = arr.filter(elm => elm);
console.log(filtered); // Prints: [1, 2, 3, -4, 5, -5, 6, 7]
In the above example the value 0 is also removed from the array because it is falsy value. However, if you want to keep it, you can define a custom filter callback function like this:
Example
Try this code »// Sample array
var arr = [1,2,,3,,-4,"",null,,0,,false,undefined,5,,-5,6,"",7,,];
// Defining a custom filter function
function myFilter(elm){
return (elm != null && elm !== false && elm !== "");
}
// Performing filtration
var filtered = arr.filter(myFilter);
console.log(filtered); // Prints: [1, 2, 3, -4, 0, 5, -5, 6, 7]
Since null == undefined
is true
elm != null
will catch both null
and undefined
values.
Also, check out the tutorial on arrow functions to learn how to write a compact and concise function expression in JavaScript using the fat arrow (=>
) notation.
Related FAQ
Here are some more FAQ related to this topic: