The Array.from() method returns an Array object from object with a length property or an iterable object.
The Array.from() method returns an Array object from object with a length property or an iterable object.
Array.from(object, mapFunction, thisValue)
Parameter | Require | Description |
---|---|---|
object | Required. | The object to convert to an array |
mapFunction | Optional. | A map function to call on each item of the array |
thisValue | Optional. | A value to use as this when executing the mapFunction |
An Array object
Create an Array from a String:
var myArr = Array.from("ABCDEFG"); console.log( myArr);
Array from() method can convert array-like objects or iterable objects into arrays.
For example, consider the following object:
To convert the object above into an array, we can do it using the Array.from() :
const customers = { '0': 'A', '1': 'B', '2': 'C', '3': 'D', '4': 'E', length: 5 //from ww w . j a v a2s .co m }; Array.from(customers).forEach(customer => { console.log(customer); });
Here, we passed into the function the customer object, and in turn it returns an array formed from the individual elements.
Array.from syntax:
Array.from(arrayLike[, mapFn[, thisArg]])
Array.from() tries to check if its first argument is an iterable.
If it is iterable Array.from() uses the iterator to produce values to copy into the returned array.
If you pass an array-like object, it behaves the same as slice() or apply() does, which is simply loop over the values accessing numerically names properties from 0 to the length of the object.
If we now use the above example with the optional mapFn argument, it would look like this:
Array.from(customers, customer => { console.log(customer); });
We have removed the forEach method and used a second argument as a map function to iterate over the resultant array.