Skip to main content

toArray()

toArray<T>(value): T[]

Normalizes a value to an array.

note

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"]