Home > Back-end >  Turning single values and arrays into arrays including zeros as single value
Turning single values and arrays into arrays including zeros as single value

Time:01-18

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:

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?

CodePudding user response:

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.

  • Related