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?

holden
  • 45
  • 3
  • Does this answer your question? [Remove empty elements from an array in Javascript](https://stackoverflow.com/questions/281264/remove-empty-elements-from-an-array-in-javascript) Probably this question has similar solutions, I would take a look. – norbitrial May 14 '20 at 14:33
  • `!= null`, but it takes all falsy values, like false and {} – Juan Caicedo May 14 '20 at 14:34
  • If you are using *lodash* library, there is already a utility [isEmpty](https://lodash.com/docs/#isEmpty) for the same. – Sunil Chaudhary May 14 '20 at 14:52

3 Answers3

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

Juan Caicedo
  • 1,425
  • 18
  • 31
  • 1
    Only `emptyVariants[1]` contains that specific empty object, most likely that same object doesn't occur anywhere else. Also detecting `null` seems to fail ... – Teemu May 14 '20 at 14:40
1

How about this?

 arr.filter(i => (typeof i === 'number') || (i && i.length>0) || (( i && Object.keys(i).length)>0) || (i===0));
ABGR
  • 4,631
  • 4
  • 27
  • 49
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)
palaѕн
  • 72,112
  • 17
  • 116
  • 136