Q:

How to Remove Empty Elements from an Array in JavaScript

0

How to Remove Empty Elements from an Array in JavaScript

All Answers

need an explanation for this answer? contact us directly to get an explanation for this 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 ""false0nullundefined, and NaN.

Let's check out the following example to understand how it basically works:

// 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:

// 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.

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

JavaScript / jQuery Frequently Asked Questions

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
How to Stop setInterval() Call in JavaScript... >>
<< How to Get Query String Parameters Values in JavaS...