PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Friday, October 28, 2022

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

 October 28, 2022     arrays, filter, is-empty, javascript     No comments   

Issue

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)



Answered By - palaѕн
Answer Checked By - Clifford M. (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing