JavaScript arrays allow you to store multiple elements of any type in a single object.
In JavaScript, null
and undefined
values are also used to denote the falsy values.
This tutorial teaches you the different methods to remove empty elements from an Array in JavaScript. It also teaches you how to remove the falsy values, including null
and undefined
.
Remove Empty Elements From an Array Using Array Filter() Method
The array filter() method creates a shallow copy of the elements in the array that passes the test condition.
Use this method when you want to remove all the empty elements, including the null
and undefined
elements. And create a new array object with the non-empty elements.
- Invoke the
filter()
method in your array object (a) => a
as the test function. This test function denotes that the element must be a truthy value to be filtered
Code
const arr = [1, , , , 2, "text", null, undefined, 5, , ];
const newArr = arr.filter((a) => a);
console.log(newArr); //[1, 2, "text", 5]
Remove Empty Elements From an Array Using Array Flat() Method
The flat() method creates a new array with all sub-array elements.
This method is usually used when you want to flatten the array elements in an array of arrays. While concatenating, it will ignore all the empty slots in the array.
Use this method when you want to remove the empty elements and don’t want to remove the null
or undefined
objects.
- Invoke the
flat()
method on your array object. Pass the0
as depth. - A new array will be created with the non-empty elements, including
null
orundefined
elements
Code
const arr = [1, , , , 2, "text", null, undefined, 5, , ];
const newArr = arr.flat(0);
console.log(newArr); // [1, 2, "text", null, undefined, 5]
Filtering Empty Strings from an Array of Strings
To filter the empty strings from an array of strings,
- Pass
boolean
as a parameter to thefilter()
method - It returns only the
truthy
values from the array
Code
var arr = ['a', 'b', '', 'c', 'd', 'e', ''];
arr = arr.filter(Boolean);
console.log(arr); //["a", "b", "c", "d", "e"]