How Lodash castArray Handles an ES6 Set
When you pass an ES6 Set instance to Lodash's
_.castArray method, the function does not convert the set's
elements into an array; instead, it wraps the entire Set
object itself as the single element inside a newly created array. This
behavior often surprises developers who expect collection conversion,
but it strictly follows the defined implementation of
_.castArray, which only checks if an input is already a
native array rather than inspecting whether it is iterable.
Under the hood, _.castArray relies on the native
Array.isArray() method. If the argument passed to it
returns true for Array.isArray(), the method
returns that argument unaltered. If it returns false, it
returns a new array with the argument placed at index 0.
Because an ES6 Set is an Object rather than an
Array, Array.isArray(new Set()) evaluates to
false.
For example, consider the following code execution:
const mySet = new Set([1, 2, 3]);
const result = _.castArray(mySet);
console.log(result);
// Output: [ Set(3) { 1, 2, 3 } ]
console.log(result.length);
// Output: 1The resulting array has a length of 1, containing the
original Set reference.
If your objective is to flatten or transform the unique items of a
Set into an array, _.castArray is not the
appropriate utility. Instead, you should use native JavaScript features
like Array.from(mySet) or the spread operator
[...mySet]. Within the Lodash library, the proper
alternative for converting an iterable collection like a
Set into an array of its elements is
_.toArray(mySet).