12
\$\begingroup\$

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?

\$\endgroup\$
1
  • 5
    \$\begingroup\$ Welcome to Code Golf! I've added the tips tag, since this is asking for a way to shorten some code in a specific language. \$\endgroup\$ Jan 22 at 6:12

2 Answers 2

19
\$\begingroup\$

10 bytes

[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.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ In older versions you can still write [].concat(r,s,t). \$\endgroup\$
    – Neil
    Jan 22 at 7:20
4
\$\begingroup\$

aparently this works t.map?t:[t]

\$\endgroup\$
1
  • 10
    \$\begingroup\$ Works, but risky. 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\$
    – jonrandy
    Jan 22 at 6:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.