[javascript] Remove empty elements from an array in Javascript

Removing all empty elements

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

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

Simple compacting (removing empty elements from an array)

With ES6:

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

With plain Javascript ->

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