How to remove empty elements from an array in JavaScript

In this tutorial, we will learn how to remove empty elements from an array in JavaScript.

To remove unnecessary elements from the array, we’ll use the filter() method.

Filtering empty strings from an array of strings

The Boolean object is a boolean value wrapped in an object. It returns false value for 0, -0, null, false, NaN, undefined, or the empty string (“”).

let arr = ['This','','is','','a','','tutorial','','in','','CodeSpeedy']
arr = arr.filter(Boolean)
console.log(arr)

Output:

["This", "is", "a", "tutorial", "in", "CodeSpeedy"]

Filtering empty arrays from an array of arrays

An empty array is an array with a length of 0. We used this technique to filter out empty arrays from an array.

let arr = [[1,2,3],[],[4,5],[],[6]]
arr = arr.filter((ele) => ele.length > 0)
console.log(arr)

Output:

[[1, 2, 3], [4, 5], [6]]

Filtering empty objects from an array of objects

An empty object is an object which has no keys i.e no values. We use Object.keys() method to get all keys of an object. We used this technique in the filter() method.

let arr = [{'js':'JavaScript'},{},{'py':'python'},{},{'java':'Java'}]
arr = arr.filter((ele) => Object.keys(ele).length > 0)
console.log(arr)

Output:

[{ js: "JavaScript" }, { py: "python" }, { java: "Java" }]

Filtering null, undefined from an array of numbers

The typeof() method returns the type of the parameter passed. Only the elements of type number are filtered from the array.

let arr = [1,2,3,,undefined,null]
arr = arr.filter((ele)=>typeof(ele) === 'number')
console.log(arr)

Output:

[1, 2, 3]

Custom filter to remove all empty elements

In this function, we’ll use custom filtering all techniques discussed previously to remove unnecessary elements from the array.

function removeEmptyElement(arr){
    return arr.filter((element) => {
        if(typeof(element) === 'object'){
    	    if(element === null){
      	        return false
            }
            else{
          if(Array.isArray(element)){
        	    return element.length > 0
                }
                else{
        	    return Object.keys(element).length > 0
                }
            }
        }
        else if(typeof(element) === 'undefined'){
    	    return false
        }
        else{
    	    return Boolean(element) || (typeof(element) === 'Number' && (element === 0 | element === -0)) 
        }
    })
}

let arr = [1,,'CodeSpeedy',null,[],undefined,{},'',[2,3],{'js':'JavaScript'}]
console.log(removeEmptyElement(arr))

Output:

[1, "CodeSpeedy", [2, 3], { js: "JavaScript" }]

Also read: How to round float numbers in JavaScript

Leave a Reply

Your email address will not be published.