Remove empty elements from an array in Javascript

后端 未结 30 2581
无人共我
无人共我 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:33

    When using the highest voted answer above, first example, i was getting individual characters for string lengths greater than 1. Below is my solution for that problem.

    var stringObject = ["", "some string yay", "", "", "Other string yay"];
    stringObject = stringObject.filter(function(n){ return n.length > 0});
    

    Instead of not returning if undefined, we return if length is greater than 0. Hope that helps somebody out there.

    Returns

    ["some string yay", "Other string yay"]
    

提交回复
热议问题