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?
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...
Another alternative is to use the jquery's .map() function:
var newArray = $.map( oldArray, function(v){
return v === "" ? null : v;
});
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
function cleanArray(actual)
{
var newArray = new Array();
for(var i = 0; i<actual.length; i++)
{
if (actual[i])
{
newArray.push(actual[i]);
}
}
return newArray;
}
$(function()
{
var old = ["Lorem", "", "ipsum"];
var newArr = cleanArray(old);
console.log(newArr)
});
</script>
Without Loop
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
$(function()
{
var arr = ["Lorem", "", "ipsum"];
arr = $.grep(arr,function(n){
return(n);
});
console.log(arr)
});
</script>
Both is tested.