Aller au contenu principal

toArray()

toArray<T>(value): T[]

Normalizes a value to an array.

remarque

Uses Array.isArray() for type discrimination — required for union types.


Type Parameters

T: T

The type of elements.


Parameters

value: Arrayable<T>

A single value or array of values.


Returns: T[]

The value wrapped in an array, or the original array if already one.


Since

2.0.0


Performance

O(1) time & space, returns original array if already one, otherwise creates single-element array.


Also known as

castArray (Lodash, Radashi) · of (Ramda, Effect) · toArray (Antfu) · ❌ (es-toolkit, Remeda, Modern Dash)


Example

toArray(5);
// => [5]

toArray([1, 2, 3]);
// => [1, 2, 3]

toArray('hello');
// => ['hello']

How it works?

Converts various values to arrays. Handles strings, iterables, and array-likes.


Use Cases

Normalize single values to arrays 📌

Convert single values to arrays to ensure consistent data structure for processing. Perfect for handling flexible inputs like string | string[].

const tags = "javascript";
const tagList = toArray(tags);
// => ["javascript"]

const multipleTags = ["react", "typescript"];
const tagList2 = toArray(multipleTags);
// => ["react", "typescript"] (unchanged)

Convert iterable collections to arrays

Transform Sets, Maps, or NodeLists into standard arrays for array methods. Essential for working with DOM APIs or unique collections.

const uniqueIds = new Set([1, 2, 3, 2, 1]);
const idArray = toArray(uniqueIds);
// => [1, 2, 3]

const buttons = document.querySelectorAll("button");
const buttonArray = toArray(buttons);
buttonArray.forEach((btn) => (btn.disabled = true));

Handle optional or nullable values safely

Wrap potentially undefined values into empty or single-item arrays. Useful for optional API fields or config values.

interface Config {
admins?: string | string[];
}

function getAdminList(config: Config): string[] {
return toArray(config.admins ?? []);
}

getAdminList({ admins: "alice@co.com" });
// => ["alice@co.com"]

getAdminList({ admins: undefined });
// => []

getAdminList({ admins: ["alice@co.com", "bob@co.com"] });
// => ["alice@co.com", "bob@co.com"]