40

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?

0

5 Answers 5

72

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...

Sign up to request clarification or add additional context in comments.

1 Comment

quote "there's no problem with looping...", well, except that looping can (not always) be very slow. have you every tried to supplement the native indexOf() function with a loop in js-fiddle. Lets just say indexOf is magnitudes faster.
13

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"]

Comments

9

Another alternative is to use the jquery's .map() function:

var newArray = $.map( oldArray, function(v){
  return v === "" ? null : v;
});

Comments

7
<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.

Comments

0

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];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.