Open In App

JavaScript Array from() Method

The JavaScript Array.from() method is used to create a new array instance from a given array. In the case of a string, every alphabet of the string is converted to an element of the new array instance, and in the case of integer values, a new array instance simply takes the elements of the given array.

 Syntax:

Array.from(object, mapFunction, thisValue);

Parameters:

Return value:

It returns a new Array instance whose elements are the same as the given array. In the case of a string, every alphabet of the string is converted to an element of the new array instance.



Example 1: In this example, we will see the basic use of the Array from() method.




console.log(Array.from("This is JavaScript Array " +"from() Method"));

Output

[
  'T', 'h', 'i', 's', ' ', 'i', 's',
  ' ', 'J', 'a', 'v', 'a', 'S', 'c',
  'r', 'i', 'p', 't', ' ', 'A', 'r',
  'r', 'a', 'y', ' ', 'f', 'r', 'o',
  'm', '(', ')', ' ', 'M', 'e', 't',
  'h', 'o', '...

Example 2: Here we see that output creates a new array whose content is the same as input in the case of an integer.




console.log(Array.from("GeeksforGeeks"));
console.log(Array.from([10, 20, 30]));

Output
[
  'G', 'e', 'e', 'k',
  's', 'f', 'o', 'r',
  'G', 'e', 'e', 'k',
  's'
]
[ 10, 20, 30 ]

Example 3: Here as we see that output creates a new array whose content is the same as input every alphabet of the string is converted to an element of the new array instance.




// Here input array is [1,2,3] and output
// become double of each elements.
console.log(Array.from([1, 2, 3],
            x => x + x));

Output
[ 2, 4, 6 ]

Note: If we take a complex number as the parameter, it returns an error because only array and string can be taken as the parameter. 

We have a complete list of Javascript Array methods, to check those please go through this Javascript Array Complete reference article.

Supported Browsers:

We have a Cheat Sheet on Javascript where we covered all the important topics of Javascript to check those please go through Javascript Cheat Sheet-A Basic guide to JavaScript.


Article Tags :