JS: Filter array only for non-empty and type of string values

后端 未结 4 1272
醉酒成梦
醉酒成梦 2021-01-21 21:52

I am trying to filter an array like this:

array.filter(e => { return e })

With this I want to filter all empty strings including undef

4条回答
  •  半阙折子戏
    2021-01-21 22:23

    You can check the type of the elements using typeof:

    array.filter(e => typeof e === 'string' && e !== '')
    

    Since '' is falsy, you could simplify by just testing if e was truthy, though the above is more explicit

    array.filter(e => typeof e === 'string' && e)
    

    const array = [null, undefined, '', 'hello', '', 'world', 7, ['some', 'array'], null]
    
    console.log(
      array.filter(e => typeof e === 'string' && e !== '')
    )

提交回复
热议问题