Search code examples
javascriptarraysfilteris-empty

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?


Solution

  • 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)