JavaScript Array from() Method
The from() method creates a new array that holds the shallow copy from an array or iterable object. When applied to a string, each word gets converted to an array element in the new array.
Syntax
There is a following possible syntax:
Parameter
- object: It is the name of the array-like or iterable object on which from() method will be applied.
- map_fun: It is an optional parameter used for calling the elements of the array via map() function.
- thisArg: An optional parameter whose value is used as ‘this’ when we execute the map_fun.
Return
It returns a newly created array.
Note: Array from() method allows to create a new array from an array-like object, specified with a length property and indexed elements. The length property of the from() method is 1 usually.
JavaScript Array from() Method Example
Let’s see the below examples to understand better:
Example1
Here’s a simple example to create an array from a string.
Output:
In the output displayed, it is clear that each letter of the string gets converted to an array element.
Example2
Here’s an example to create an array from an array-like object.
Output:
Example3
Here’s an example to convert a given Set into an array.
Output:
In the output, we can see that each value occurred only once.
Note: A set is a collection of values that occur only once in the resultant/output. Such behavior maintains the uniqueness of each value present in the set.
Example1
Here’s an example of generating a sequence of numbers using length property.
Output: