I have an array ["Lorem", "", "ipsum"]
. I would like to remove the empty string from this array and get ["Lorem", "ipsum"]
.
Is there any way to do this without using the loop and traversing through each element and removing it?
To remove the empty strings from an array, we can use the filter() method in JavaScript. In the above code, we have passed the callback function e => e to the filter method, so that it only keeps the elements which return true . empty "" string is falsy value, so it removes from the array.
Method #1: Using remove() This particular method is quite naive and not recommended use, but is indeed a method to perform this task. remove() generally removes the first occurrence of an empty string and we keep iterating this process until no empty string is found in list.
You may use filter
:
var newArray = oldArray.filter(function(v){return v!==''});
The MDN has a workaround for IE8 compatibility. You might also use a good old loop if you're not going to use filter
anywhere else, there's no problem with looping...
If you use Javascript 1.6 (probably wont work on IE8 or less) you can use
arr.filter(Boolean) //filters all non-true values
eg.
console.log([0, 1, false, "", undefined, null, "Lorem"].filter(Boolean)); // [1, "Lorem"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With