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

后端 未结 4 1231
醉酒成梦
醉酒成梦 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 !== '')
    )

    0 讨论(0)
  • 2021-01-21 22:23

    You could check for a string and empty both in your filter method:

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

    Note: !!e returns false if the element is null, undefined, '' or 0.

    I should mention that the "arrow"-function syntax only works in browsers that support ES6 or higher.

    The alternative is:

    array.filter(function(e) {
        return (typeof e === 'string') && !!e;
    });
    

    Note: Keep in mind that Array.prototype.filter doesn't exist in older browsers.

    0 讨论(0)
  • 2021-01-21 22:35

    When returning a method that consists of one line as a callback in es6 there is no need for return as this happens implicitly.

    Hope this helps :-)

    let arr = ["", "", "fdsff", [], null, {}, undefined];
    
    let filteredArr = arr.filter(item => (typeof item === "string" && !item) || !item)
                      
    console.log(filteredArr)

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题