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

Turning single values and arrays into arrays including zeros as single value

While I was searching for a good way to check if a function variable is an array or a single variable and then turn both into arrays for further processing, I came across this post.

The answer provided by @VoteyDisciple

var eventsArray = events ? [].concat(events) : [];

works great for me until events is a single variable with a value of zero. In that case, eventsArray will be empty. Here is my entire code:

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

var eventsArray = [];
if (!(Array.isArray(events))) {
  eventsArray = events ? [].concat(events) : [];
} else {
  eventsArray = events;
}

I have tried to make another if-statement before the else line to catch this special occasion. But that ends up in a mess for the rest of the code and I doubt it’s very elegant. Therefore I wonder if it is possible to change this line:

eventsArray = events ? [].concat(events) : [];

in a way so that if events is a single variable with a value of zero, this line will also turn this occasion into an array with a single element and a value of zero?

For understanding things better, I also want to ask: Why does this line of code "lose" the zero but works great with any other single value?

>Solution :

It’s much simpler:

eventsArray = Array.isArray(events) ? events : [events];

The reason you lose the zero is because zero is falsey in a boolean context like the conditional operator. You’ll also lose null and empty strings.

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