Array.from
The Array.from()
static method creates a new, shallow-copied Array
instance from an iterable or array-like object.
Syntax
Array.from(arrayLike)
// Arrow function
Array.from(arrayLike, (element) => { /* … */ })
Array.from(arrayLike, (element, index) => { /* … */ })
// Mapping function
Array.from(arrayLike, mapFn)
Array.from(arrayLike, mapFn, thisArg)
// Inline mapping function
Array.from(arrayLike, function (element) { /* … */ })
Array.from(arrayLike, function (element, index) { /* … */ })
Array.from(arrayLike, function (element) { /* … */ }, thisArg)
Array.from(arrayLike, function (element, index) { /* … */ }, thisArg)
Parameters
arrayLike
- : An iterable or array-like object to convert to an array.
mapFn
optional: Map function to call on every element of the array. If provided, every value to be added to the array is first passed through this function, and
mapFn
's return value is added to the array instead.The function is called with the following arguments:
element
- : The current element being processed in the array.
index
- : The index of the current element being processed in the array.
thisArg
optional- : Value to use as
this
when executingmapFn
.
- : Value to use as
Return value
A new Array
instance.
Description
Array.from()
lets you create Array
s from:
- iterable objects (objects such as
Map
andSet
; or, if the object is not iterable, - array-like objects (objects with a
length
property and indexed elements).
Array.from()
never creates a sparse array. If the arrayLike
object is missing some index properties, they become undefined
in the new array.
Array.from()
has an optional parameter mapFn
, which allows you to execute a function on each element of the array being created, similar to Array.prototype.map()
. More clearly, Array.from(obj, mapFn, thisArg)
has the same result as Array.from(obj).map(mapFn, thisArg)
, except that it does not create an intermediate array, and mapFn
only receives two arguments (element
, index
) without the whole array, because the array is still under construction.