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
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.
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)
const justStrings = array.filter(element =>
(typeof element === 'string' || element instanceof String)
&& element
)
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.