I am trying to filter an array like this:
array.filter(e => { return e })
With this I want to filter all empty strings including undefined and null.
Unfortunately my array have some arrays, which should not be there. So I need also to check only for string values and remove all other.
How do I do that?
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 !== '')
)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With