The from function generates a fresh array that contains a shallow copy derived from an existing array or any iterable object. When this function is used on a string, each individual word is transformed into an element within the newly created array.
Syntax
There is a following possible syntax:
Array.from(object,map_fun,thisArg);
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 us examine the following examples for a clearer understanding:
Example1
Below is a straightforward illustration of how to generate an array from a string.
<html>
<head> <h5> JavaScript Array Methods </h5> </head>
<body>
<script>
var arr=Array.from("You are viewing an example of string"); //The string will get converted to an array.
document.write("The resultant is: <br>" +arr);
</script>
</body>
</html>
Output:
The output presented indicates that every character in the string is transformed into an element of an array.
Example2
Below is an illustration demonstrating how to generate an array from an object that resembles an array.
<html>
<head> <h5> JavaScript Array Methods </h5> </head>
<body>
<script>
var func = function() {
document.write(Array.from(arguments)); //Using from() method
}
func('John','Roy','Jess','Mary'); //value passed to function f().
</script>
</body>
</html>
Output:
Example3
Below is an illustration of how to transform a specified Set into an array.
<html>
<head> <h5> JavaScript Array Methods </h5> </head>
<body>
<script>
var set = new Set(['C','C++','Java','C','Java','C++','Python','Perl']); //A set of different values.
document.write(Array.from(set)); //Using from() will convert the given set into an array.
</script>
</body>
</html>
Output:
In the results displayed, it is evident that each value appeared solely one time.
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
Below is an illustration of how to create a sequence of numbers by utilizing the length attribute.
<html>
<head> <h5> JavaScript Array Methods </h5> </head>
<body>
<script>
document.write(Array.from({length: 9}, (v, i) => i)); //Here, array is initialized as undefined. Thus, value of v and i are undefined.
</script>
</body>
</html>
Output: