Remove empty elements from an array in Javascript

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

    With Underscore/Lodash:

    General use case:

    _.without(array, emptyVal, otherEmptyVal);
    _.without([1, 2, 1, 0, 3, 1, 4], 0, 1);
    

    With empties:

    _.without(['foo', 'bar', '', 'baz', '', '', 'foobar'], '');
    --> ["foo", "bar", "baz", "foobar"]
    

    See lodash documentation for without.

提交回复
热议问题