user3142695
user3142695

Reputation: 17352

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?

Upvotes: 4

Views: 12421

Answers (5)

Aymen Jarouih
Aymen Jarouih

Reputation: 514

You can use this snippet to filter by instance of / type of

arr.filter((item) => item instanceof String);

Upvotes: 0

Roman
Roman

Reputation: 5220

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.

Upvotes: 1

Francis Leigh
Francis Leigh

Reputation: 1960

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)

Upvotes: 0

cyr_x
cyr_x

Reputation: 14257

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.

Upvotes: 4

Craig Ayre
Craig Ayre

Reputation: 1173

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 !== '')
)

Upvotes: 12

Related Questions