Remove empty elements from an array in Javascript

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

    For removing holes, you should use

    arr.filter(() => true)
    arr.flat(0) // Currently stage 3, check compatibility before using this
    

    For removing hole, and, falsy (null, undefined, 0, -0, NaN, "", false, document.all) values:

    arr.filter(x => x)
    

    For removing hole, null, and, undefined:

    arr.filter(x => x != null)
    

    arr = [, null, (void 0), 0, -0, NaN, false, '', 42];
    console.log(arr.filter(() => true)); // [null, (void 0), 0, -0, NaN, false, '', 42]
    console.log(arr.filter(x => x)); // [42]
    console.log(arr.filter(x => x != null)); // [0, -0, NaN, false, "", 42]

提交回复
热议问题