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

Return undefined on empty nested arrays with flat

I’m using flat() to count the number of empty or undefined items inside a nested array.

[[undefined, 4], [4]]

Using flat on this array will return 3 items:

  1. undefined
  2. 4
  3. 4

However on this array:

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

[[], [], []]

using flat will return an empty array.

Is there a way to use it so it returns 3 undefined items?

>Solution :

You have to use flatMap for this reason:

[[], [], []].flatMap(item => item.length ? item : undefined)

returns what you need

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