Array.from
Creates an array from a string, Set, Map or another iterable.
Available since: ES2015
Syntax
Array.from(items, mapFn)Parameters
| Parameter | Type | Description |
|---|---|---|
| items | Iterable | object | What to turn into an array: a string, Set, Map, iterator or an object with a length property. |
| mapFn | Function | Optional. A function that transforms each element. |
Return value
ArrayA new array.
Examples
A string into an array of characters:
console.log(Array.from('hey'));Output:
[
"h",
"e",
"y"
]Unique values from a Set:
const unique = Array.from(new Set([1, 2, 2, 3]));
console.log(unique.join(', '));Output:
1, 2, 3An array of a given length, filled by a function:
console.log(Array.from({ length: 5 }, (_, i) => i * 10).join(', '));Output:
0, 10, 20, 30, 40Notes
The second argument works like map() without creating an intermediate array.
See also
- Array.of — Creates an array from its arguments.
- Spread syntax — Three dots spread an array or object into separate items.
- Array.prototype.map — Creates a new array by transforming every element.
Related recipes
In the tutorial
- Arrays — What an array is in JavaScript: creating one, indexes, length, changing elements and nested arrays.