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?
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.
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];
}
If you use ES6, you can do the following, it's cleaner than .concat()
;
function method(value = []) {
const array = [...value];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With