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

后端 未结 4 1232
醉酒成梦
醉酒成梦 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:41

    const justStrings = array.filter(element => 
        (typeof element === 'string' || element instanceof String)
        && element
    )
    

    Explanation

    To be shure your element is a string you have to check that it isn't a variable type (let str = 'hello') or an instance of String (new String('hello')) because this case would return object by typeof element.

    Additionally you have to check if your element exists.

提交回复
热议问题