Encodera

Thanks for reading!

Donate to the site — we work hard for you.

JavaScript reference

Array.from

Creates an array from a string, Set, Map or another iterable.

Available since: ES2015

Syntax

Array.from(items, mapFn)

Parameters

ParameterTypeDescription
itemsIterable | objectWhat to turn into an array: a string, Set, Map, iterator or an object with a length property.
mapFnFunctionOptional. 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, 3

An array of a given length, filled by a function:

console.log(Array.from({ length: 5 }, (_, i) => i * 10).join(', '));

Output:

0, 10, 20, 30, 40

Notes

The second argument works like map() without creating an intermediate array.

See also

Related recipes

In the tutorial

  • Arrays — What an array is in JavaScript: creating one, indexes, length, changing elements and nested arrays.

Thanks for reading!

Donate to the site — we work hard for you.