I have an array [\"Lorem\", \"\", \"ipsum\"]
. I would like to remove the empty string from this array and get [\"Lorem\", \"ipsum\"]
.
Is th
var arr = [ a, b, c, , e, f, , g, h ];
arr = jQuery.grep(arr, function(n){ return (n); });
arr is now [ a, b, c, d, e, f, g];
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"]
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.