Array. from()
Creates an array from an iterable or "array-like" object.
- Returns
- A new array.
- Changes the original
- No
Example
#console.log(Array.from('web'))
console.log(Array.from(new Set([1, 2, 2, 3])))
console.log(Array.from({ length: 5 }, (_, i) => i + 1))Definition and usage
#The static Array.from() method turns anything iterable, or anything with a length property, into a real array: a string, a Set, a Map, a DOM element list (NodeList), or an object like { length: 3 }.
The second argument is a mapping function, called for every element. That makes it easy to generate an array of numbers: Array.from({ length: 5 }, (_, i) => i + 1).
In many cases the spread syntax [...iterable] does the same thing, but Array.from() also works with objects that only have length, and maps right away.
Syntax
#Array.from(arrayLike)
Array.from(arrayLike, mapFn)Parameters
#arrayLike
iterable or object with length
The source of the elements, such as a string, a Set, or a NodeList.mapFn
optional function (element, index)
A function that transforms every element.
Browser support
#Widely available
Works in all modern browsers, phones included. You can use it without worry.
- Chrome
- Edge
- Firefox
- Safari
Good practices
#- You can get an array’s unique values with
Array.from(new Set(array))or[...new Set(array)]. - The list from
querySelectorAll()doesn’t have every array method.Array.from()fixes that.
Related entries
#- Array.isArray()Checks whether a value is an array.
- Spread (...)The spread syntax spreads an array, string, or object out into individual elements: for copying, merging, and passing arguments.
- SetA collection of unique values: each value can appear in the set only once.
- document.querySelectorAll()Returns a static list (NodeList) of every element that matches a CSS selector.
- Array.of()Creates a new array from the given arguments, regardless of how many there are or their type.
- Iterators (Symbol.iterator)The iteration protocol: an object with a [Symbol.iterator]() method works with for...of, spread, and destructuring.
Spotted a mistake or missing an example? Write to us.