Remove empty elements from an array in Javascript

后端 未结 30 3079
无人共我
无人共我 2020-11-21 09:53

How do I remove empty elements from an array in JavaScript?

Is there a straightforward way, or do I need to loop through it and remove them manually?

30条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2020-11-21 10:31

    If you need to remove ALL empty values ("", null, undefined and 0):

    arr = arr.filter(function(e){return e}); 
    

    To remove empty values and Line breaks:

    arr = arr.filter(function(e){ return e.replace(/(\r\n|\n|\r)/gm,"")});
    

    Example:

    arr = ["hello",0,"",null,undefined,1,100," "]  
    arr.filter(function(e){return e});
    

    Return:

    ["hello", 1, 100, " "]
    

    UPDATE (based on Alnitak's comment)

    In some situations you may want to keep "0" in the array and remove anything else (null, undefined and ""), this is one way:

    arr.filter(function(e){ return e === 0 || e });
    

    Return:

    ["hello", 0, 1, 100, " "]
    

提交回复
热议问题