Turning a single value into an array

Viewed 4294

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?

5 Answers

A condensed ES2020 way to ensure a variable is an array:

value = [].concat(value ?? [])

Explanation

As @VoteyDisciple explained, the concat function will concatenate single values or an arrays of values. The nullish coalescing operator (??) will use the value on the right (the second empty array) if the value on the left is null or undefined. So if value is null, it will concatenate an empty array to an empty array, which returns an empty array.

Examples

// Different inputs and outputs
values = [].concat([1,2,3] ?? [])   // [1,2,3]
values = [].concat(1 ?? [])         // [1]
values = [].concat(null ?? [])      // []

// Wrap it in a function if you like
function array(value) {
    return [].concat(value ?? [])
}

// Use it like this
values = array(values)

// Or even like this
for (let value of array(values)) {
    console.log(value)
}
Related