Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Filtering an array with an empty array

const arrFilter = [{id:1},[],[]];

how can I filter the empty array in the above example, so that the result would be the object with an id only

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You can use the length of the array returned from Object.keys() to determine if objects, arrays or strings are empty however it won’t work on numbers.

With that in mind, try this assuming that

  • all empty objects, arrays and strings should be omitted
  • everything else stays
const arrFilter = [{id:1},[],[], "a string", "", 1, 0];

const nonEmpties = arrFilter.filter(
  (item) => typeof item === "number" || Object.keys(item).length > 0
);
  
console.log(nonEmpties);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading