Remove empty strings from array while keeping record Without Loop?

后端 未结 7 1554
臣服心动
臣服心动 2020-11-28 20:55

This question was asked here: Remove empty strings from array while keeping record of indexes with non empty strings

If you\'d notice the given as @Baz layed it out;

相关标签:
7条回答
  • 2020-11-28 21:20
    arr = arr.filter(v => v);
    

    as returned v is implicity converted to truthy

    0 讨论(0)
  • 2020-11-28 21:26

    If are using jQuery, grep may be useful:


    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-11-28 21:28
    var newArray = oldArray.filter(function(v){return v!==''});
    
    0 讨论(0)
  • 2020-11-28 21:30
    var arr = ["I", "am", "", "still", "here", "", "man"]
    // arr = ["I", "am", "", "still", "here", "", "man"]
    arr = arr.filter(Boolean)
    // arr = ["I", "am", "still", "here", "man"]
    

    filter documentation


    // arr = ["I", "am", "", "still", "here", "", "man"]
    arr = arr.filter(v=>v!='');
    // arr = ["I", "am", "still", "here", "man"]
    

    Arrow functions documentation

    0 讨论(0)
  • 2020-11-28 21:34

    You can use lodash's method, it works for string, number and boolean type

    _.compact([0, 1, false, 2, '', 3]);
    // => [1, 2, 3]
    

    https://lodash.com/docs/4.17.15#compact

    0 讨论(0)
  • 2020-11-28 21:39

    i.e we need to take multiple email addresses separated by comma, spaces or newline as below.

        var emails = EmailText.replace(","," ").replace("\n"," ").replace(" ","").split(" ");
        for(var i in emails)
            emails[i] = emails[i].replace(/(\r\n|\n|\r)/gm,"");
    
        emails.filter(Boolean);
        console.log(emails);
    
    0 讨论(0)
提交回复
热议问题