Nick Bull
Nick Bull

Reputation: 9866

Elegant way to transform an object to an array

Let's say I have a function that returns either an array or a value:

const a = f(...);
// a === [ 1 ];

const b = f(...);
// b = 1;

What is the most elegant way to transform the returned value into an array, so that a === b?

I was hoping something like [ ...b ] would work, but it throws. The solution I have come to so far is Array.isArray(b) ? b : [ b ], but I'm curious if there's a cleaner way to do this, preferably a single function/non-branching expression

Upvotes: 0

Views: 50

Answers (3)

Saurabh Tiwari
Saurabh Tiwari

Reputation: 5131

Perhaps a way out is to use the construct

Array.from()

Example:

Array.from(a());

and

Array.from(b());

Both should return you the result in an array.

Upvotes: 0

Ele
Ele

Reputation: 33726

The function Array.prototype.concat accepts either an array or a single value as a parameter.

This is assuming you want an array always.

//This is just to illustrate.
const f = (asArray) => asArray ? [1] : 1,
      a = [].concat(f(true)),
      b = [].concat(f(false));

console.log(a.length === b.length && a[0] === b[0]);

Upvotes: 1

hgb123
hgb123

Reputation: 14881

You could do

return [b].flat()

Upvotes: 1

Related Questions