Materialize iterable values
Turn strings, Sets, Maps, or other iterables into ordinary arrays for indexed access and array methods.
JavaScript · Function
Array.from() creates a new Array from an iterable or array-like object. An optional callback can transform each value as the result is built.
Array.from() accepts an iterable or an array-like value, creates a new Array, and optionally transforms each source element with mapFn before placing it in the result. For array-like inputs, it uses indexed properties up to length; for iterable inputs, it follows iteration order.
Array.from(items)
Array.from(items, mapFn)
Array.from(items, mapFn, thisArg)| Name | Type | Description |
|---|---|---|
items | Iterable or array-like object | The iterable or array-like object to convert into an array. |
mapFn | Function | Optional function called for each element; its return value is stored in the result. |
thisArg | Any | Optional value used as this when invoking mapFn. |
A new Array instance.
const text = "hello";
const upper = Array.from(text, (char, index) =>
`${index}:${char.toUpperCase()}`
);
console.log(upper);
// ["0:H", "1:E", "2:L", "3:L", "4:O"]Creates an array from the string and transforms each character during creation.
Turn strings, Sets, Maps, or other iterables into ordinary arrays for indexed access and array methods.
Convert DOM collections or custom objects with length and indexed properties into arrays.
Apply a one-step conversion and transformation without a separate map pass.
Array.from() creates a new shallow Array from an iterable or an array-like object. Its optional mapFn transforms values while the result is being built.
Follow-up: How does it treat a string? A string is iterable, so characters are processed in iteration order rather than by enumerating ordinary object keys.
For an iterable, Array.from() follows the iterable's values. For an array-like object, it reads indexed properties according to the object's length.
Follow-up: What happens when an array-like object lacks an indexed property? The corresponding result position contains undefined, keeping the result dense.
mapFn is optional and is called for each source element; its returned value is inserted into the new array. The callback receives the element and index, and thisArg can provide its this binding.
Follow-up: Why prefer mapFn over Array.from(source).map(fn) when both work? It performs the transformation as the array is created and avoids requiring a separate intermediate array.
Array.fromAsync()Array.prototype.map()Object.keys()Object.values()Object.entries()Set