JavaScriptArrays

Array.from()

Creates an array from an iterable or "array-like" object.

Returns
A new array.
Changes the original
No
On this page

Example

#
JavaScript
console.log(Array.from('web'))
console.log(Array.from(new Set([1, 2, 2, 3])))
console.log(Array.from({ length: 5 }, (_, i) => i + 1))
Console
['w', 'e', 'b']
[1, 2, 3]
[1, 2, 3, 4, 5]

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

#
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

#

Spotted a mistake or missing an example? Write to us.