Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Turning a single value into an array

In my project I often find myself checking if a value is an array.

If the value is not an array I create a single element array from it.

If the value is undefined or null, I create an empty array.

The value itself is usually either an array of objects or a single object or undefined

const array = value ? (Array.isArray(value) ? value: [value]) : [];

Is there a more succinct way of doing this (perhaps with lodash or underscore), before I decide to factor this into a separate util function?

like image 850
krl Avatar asked Mar 11 '16 15:03

krl


3 Answers

You could do

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

The .concat() function accepts both arrays and individual arguments, so either way you end up with what you want.

like image 80
VoteyDisciple Avatar answered Sep 30 '22 18:09

VoteyDisciple


since you are using const in your code I assume you are using ES2015 / ES6. ES1015's Default function parameters allow formal parameters to be initialized with default values if no value or undefined is passed.

function abc(value = []) {

  const array =  Array.isArray(value) ? value: [value];

}
like image 20
Darshan Avatar answered Sep 30 '22 19:09

Darshan


If you use ES6, you can do the following, it's cleaner than .concat();

function method(value = []) {
  const array = [...value];
}
like image 31
Michael Avatar answered Sep 30 '22 18:09

Michael