JavaScript Array from() Method

JavaScript Array from() Method creates a new array that holds the shallow copy from an array or iterable object.

Array.from() is a static property of the JavaScript Array object.

You can only use it as Array.from().

The Array.from() method returns an array from any object with a length property.

The Array.from() method returns an array from any iterable object.

Syntax

Array.from(object, mapFunction, thisValue)

Parameters

This method accepts three parameters as mentioned above and described below:

  • object- Required. The object to convert to an array.
  • mapFunction – Optional. A map function to call on each item.
  • thisValue – Optional. A value to use as this for the mapFunction

Return Value

It returns a newly created array.

Examples

Below are the examples of the Array from() method.

console.log(Array.from('foo'));
// expected output: Array ["f", "o", "o"]

console.log(Array.from([1, 2, 3], x => x + x));
// expected output: Array [2, 4, 6]

Array from a String

In the case of a string, every alphabet of the string is converted to an element of the new array instance and in case of integer values, a new array instance simply takes the elements of the given array.

Array.from('foo');
// [ "f", "o", "o" ]

Array from a Set

const set = new Set(['foo', 'bar', 'baz', 'foo']);
Array.from(set);
// [ "foo", "bar", "baz" ]

Array from a Map

const map = new Map([[1, 2], [2, 4], [4, 8]]);
Array.from(map);
// [[1, 2], [2, 4], [4, 8]]

const mapper = new Map([['1', 'a'], ['2', 'b']]);
Array.from(mapper.values());
// ['a', 'b'];

Array.from(mapper.keys());
// ['1', '2'];