Below is the example of the Array from() method.
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,d
The arr.from() method is used to creates 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 case of integer values, a new array instance simply takes the elements of the given array.
Array.from(object, mapFunction, thisValue)
Parameters: This method accepts three parameters as mentioned above and described below:
- object: This pareter holds that object that will convert into an array
- mapFunction: This parameter is optional used to call on each item of the array.
- thisValue: This parameter is optional, it holds the context to be passed as this to be used while executing the mapFunction. If the context is passed, it will be used like this for each invocation of the callback function, otherwise undefined is used as default.
Return value: It returns a new Array instance whose elements are 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: Here as we see that output creates a new array whose content is the same as input in case of a integer.
Input : 10, 20, 30 Output: Array [10, 20, 30]
- Example 2: 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.
Input : geeksforgeeks Output: Array ["g", "e", "e", "k", "s", "f", "o", "r", "g", "e", "e", "k", "s"]
Code for the above method is provided below:
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.
- Google Chrome 45.0
- Microsoft Edge 12.0
- Mozilla Firefox 32.0
- Safari 9.0
- Opera 25.0