Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 819
user3142695 Avatar asked Dec 04 '22 21:12

user3142695


2 Answers

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 !== '')
)
like image 176
Craig Ayre Avatar answered Dec 06 '22 11:12

Craig Ayre


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.

like image 40
cyr_x Avatar answered Dec 06 '22 12:12

cyr_x