Remove empty elements from an array in Javascript

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

    Simply one liner:

    [1, false, "", undefined, 2].filter(Boolean); // [1, 2]
    

    or using underscorejs.org:

    _.filter([1, false, "", undefined, 2], Boolean); // [1, 2]
    // or even:
    _.compact([1, false, "", undefined, 2]); // [1, 2]
    

提交回复
热议问题