holden
holden

Reputation: 45

How to remove different types of empty values (elements) from JS array

Have an array

const arr = [1, 'abc', [], ['John'], {}, {name: 'Smith'}, null, 0];

How to get new array without empty values? (empty array and empty object are also reckoned as empty values).

My variant seems to be a bit of hardcoded:

const newArr = arr.filter(elem => 
            (elem && Object.keys(elem).length !== 0) 
            || (typeof(elem) == 'number' && elem !== 0));

If is it possible to write less or simplier conditions?

Upvotes: 2

Views: 68

Answers (3)

Juan Caicedo
Juan Caicedo

Reputation: 1523

If you have specific variants you can try

const emptyVariants = ['', 0, null,] // all expected variants
const newArr = arr.filter(elem => !emptyVariants.includes(elem);

Another approach that you can try is using != but it takes all falsy values

const newArr = arr.filter(elem => (elem != null));

For more information see != and == operator https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Comparison_Operators

Upvotes: 2

palaѕн
palaѕн

Reputation: 73926

For the falsy values, empty object and array you have to use this part:

elem && Object.keys(elem).length !== 0

But you can minimise it like:

elem && Object.keys(elem).length

as any value for length > 0 will return as truthy.

Also, you can minimise the number logic like:

arr.filter(elem => Number(elem));

So, the final version will be like:

const arr = [1, 'abc', [], ['John'], {}, {name: 'Smith'}, null, 0];
const newArr = arr.filter(a => (a && Object.keys(a).length) || Number(a));
console.log(newArr)

Upvotes: 1

ABGR
ABGR

Reputation: 5235

How about this?

 arr.filter(i => (typeof i === 'number') || (i && i.length>0) || (( i && Object.keys(i).length)>0) || (i===0));

Upvotes: 1

Related Questions