Normalize iterable data
Convert strings, Sets, Maps, generators, or other iterable values before using array methods.
JS Puzzles · Const
Array.from turns an iterable or array-like value into a real array. It can also transform each item while building that array.
Array.from takes an iterable or array-like value, creates a new ordinary array, and copies its elements in iteration order. An optional mapping function can transform each element during creation, with an optional thisArg supplying its this value.
Array.from(obj[, mapFn, thisArg])| Name | Type | Description |
|---|---|---|
obj | iterable | array-like | An iterable or array-like value to convert into a real array. |
mapFn | function | Optional function applied to each element before it is added. |
thisArg | any | Optional this value used while mapFn runs. |
A new, ordinary Array containing the copied values.
const chars = Array.from("hello");
const doubled = Array.from(new Set([1, 2, 2]), n => n * 2);
console.log(chars); // ["h", "e", "l", "l", "o"]
console.log(doubled); // [2, 4]Converts a string and a Set into ordinary arrays; the mapping function transforms each Set value before it is added.
Convert strings, Sets, Maps, generators, or other iterable values before using array methods.
Create a transformed array in one operation with the optional mapping callback.
Convert array-like objects such as indexed collections into ordinary arrays.
Array.from creates a new real Array from an iterable or array-like object. For an iterable, it reads values through the iterable protocol and places them into the new array.
Follow-up: How does it differ from spread syntax? Array.from supports array-like objects as well as iterables, whereas spread syntax only supports iterables.
The second argument is mapFn, which runs for every source element before that element is inserted into the result. The third argument, thisArg, sets the this value used by mapFn.
Follow-up: Why use Array.from with mapFn instead of calling map afterward? It performs conversion and transformation in one creation step, avoiding a separate mapping pass.
Array.from returns a new Array instance and does not mutate the source. It also produces a dense array, so absent indexed properties become undefined rather than holes.
Follow-up: What should be used for an async iterable? Use Array.fromAsync, which is specifically documented for asynchronous iteration.
iterableSymbol.iteratoriteratormapFnthisArgArray.fromAsyncspread syntax