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

后端 未结 4 1233
醉酒成梦
醉酒成梦 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 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.

提交回复
热议问题