remove an empty string from array of strings - JQuery

后端 未结 5 1680
无人及你
无人及你 2020-12-13 18:00

I have an array [\"Lorem\", \"\", \"ipsum\"]. I would like to remove the empty string from this array and get [\"Lorem\", \"ipsum\"].

Is th

相关标签:
5条回答
  • 2020-12-13 18:44

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

    0 讨论(0)
  • 2020-12-13 18:46

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

    0 讨论(0)
  • 2020-12-13 18:46

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

    0 讨论(0)
  • 2020-12-13 18:53

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

    var newArray = $.map( oldArray, function(v){
      return v === "" ? null : v;
    });
    
    0 讨论(0)
  • 2020-12-13 18:53
    <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.

    0 讨论(0)
提交回复
热议问题