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:
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:
// 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]
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.
Use the
filter()MethodYou 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, andNaN.Let's check out the following example to understand how it basically works:
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:
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.
need an explanation for this answer? contact us directly to get an explanation for this answer