Remove empty elements from an array in Javascript

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

    Removing all empty elements

    If an array contains empty Objects, Arrays, and Strings alongside other empty elements, we can remove them with:

    const arr = [ [], ['not', 'empty'], {}, { key: 'value' }, 0, 1, null, 2, "", "here", " ", 3, undefined, 3, , , , , , 4, , 4, , 5, , 6, , , ]
    
    let filtered = JSON.stringify(
      arr.filter((obj) => {
        return ![null, undefined, ''].includes(obj)
      }).filter((el) => {
        return typeof el != "object" || Object.keys(el).length > 0
      })
    )
    
    console.log(JSON.parse(filtered))

    Simple compacting (removing empty elements from an array)

    With ES6:

    const arr = [0, 1, null, 2, "", 3, undefined, 3, , , , , , 4, , 4, , 5, , 6, , , ,]
    
    let filtered = arr.filter((obj) => { return ![null, undefined].includes(obj) })
    
    console.log(filtered)

    With plain Javascript ->

    var arr = [0, 1, null, 2, "", 3, undefined, 3, , , , , , 4, , 4, , 5, , 6, , , ,]
    
    var filtered = arr.filter(function (obj) { return ![null, undefined].includes(obj) })
    
    console.log(filtered)

提交回复
热议问题