In this article, you’ll learn how to remove empty, null, or undefined elements from an array in javascript. In Javascript, there are various ways to remove empty, null
, NaN
, or undefined
elements from an array.
Here are some examples of empty, null
, NaN
, or undefined
elements from an array in javascript.
In this example, we used the array filter()
method and passed a function to the method which returns the element currently getting looped.
filter()
method works because when an empty, null or undefined item is looped, it evaluates to a boolean value false
which will then be filtered out from the array.// array with empty, null, NaN, false or undefined elements
const arr = [1, , , "", 2, 3, 4, 56, "text", null, undefined, 67, , 77, 89, null, NaN, false];
// use filter() array method
// and return the element which is being looped
const newArr = arr.filter((a) => a);
console.log(newArr);
//Output => [1, 2, 3, 4, 56, "text", 67, 77, 89]
In this example, we used the for
loop and check if the element exists and if it exists push to the new array:
// array with empty, null, NaN, false or undefined elements
const arr = [1, , , "", 2, 3, 4, 56, "text", null, undefined, 67, , 77, 89, null, NaN, false];
// make a new array
// to hold non-empty values
const newArr = [];
// use for loop
// check if element exists
// and if it exists push to the
// new array
for (let i = 0; i < arr.length; i++) {
if (arr[i]) {
newArr.push(arr[i]);
}
}
console.log(newArr);
//Output => [1, 2, 3, 4, 56, "text", 67, 77, 89]
In this example, we used the Array.forEach()
Method. This method takes a callback function to iterate through all the elements in the array and pushes non-empty and truthy values to a new array.
// array with empty, null or undefined elements
const arr = [1, , , "", 2, 3, 4, 56, "text", null, undefined, 67, , 77, 89, null, NaN, false];
// make a new array
// to hold non-empty values
const newArr = [];
// use for loop
// check if element exists
// and if it exists push to the
// new array
arr.forEach((element)=>{
if (!!element) {
newArr.push(element);
}
});
console.log(newArr);
//Output => [1, 2, 3, 4, 56, "text", 67, 77, 89]
I hope this article will help you to understand how to remove empty elements from an array in javascript.
Share your valuable feedback, please post your comment at the bottom of this article. Thank you!
Comments