Remove empty elements from an array in Javascript

后端 未结 30 2637
无人共我
无人共我 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条回答
  •  闹比i
    闹比i (楼主)
    2020-11-21 10:38

    Just ES6 and newer versions method, assume array is below:

     const arr = [1,2,3,undefined,4,5,6,undefined,7,8,undefined,undefined,0,9];
    

    Simple way:

     const clearArray = arr.filter( i => i );
    

提交回复
热议问题