Given a variable a (non array) or (any[]) convert to (any[])
function example(s: string | string[]) {
const e = Array.isArray(s) ? s: [s]
return e
}
Is Array.isArray(s) ? s: [s]
the shortest way?
Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It only takes a minute to sign up.
Sign up to join this communityGiven a variable a (non array) or (any[]) convert to (any[])
function example(s: string | string[]) {
const e = Array.isArray(s) ? s: [s]
return e
}
Is Array.isArray(s) ? s: [s]
the shortest way?
[s].flat()
This works by doing a shallow flat on [s]
. So, if s
is anything other than an array, nothing can be flattened and it will stay as [s]
. But if s
is an array, the outer []
will be flattened away, leaving a shallow clone of s
.
Note that you can also use this to concat a number of arrays, either with other arrays or non-array elements:
[r,s,t].flat()
This is actually a trick I wasn't aware of until now. It's still a byte longer than concat
though, if the first item's guaranteed to be an array:
r.concat(s,t)
When r
could be anything, [r,s,t].flat()
seems to be the best option.
[].concat(r,s,t)
.
\$\endgroup\$
aparently this works t.map?t:[t]
t
might be a different type of object with a map
property. If you want to go down this route, t.to?t:[t]
would also work in a modern browser
\$\endgroup\$