2

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?

3
  • Does this answer your question? Remove empty elements from an array in Javascript Probably this question has similar solutions, I would take a look. Commented May 14, 2020 at 14:33
  • != null, but it takes all falsy values, like false and {} Commented May 14, 2020 at 14:34
  • If you are using lodash library, there is already a utility isEmpty for the same. Commented May 14, 2020 at 14:52

3 Answers 3

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

Only emptyVariants[1] contains that specific empty object, most likely that same object doesn't occur anywhere else. Also detecting null seems to fail ...
1

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)

2 Comments

Thanks, it does work. And advice to minimise was pretty reasonable
I believe 0 should be included in the result as 'non-empty' value. Above code excludes that.
1

How about this?

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.