Javascript - Array from() Method

The Array.from() method returns an Array object from object with a length property or an iterable object.

Description

The Array.from() method returns an Array object from object with a length property or an iterable object.

Syntax

Array.from(object, mapFunction, thisValue)

Parameter Values

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

Return

An Array object

Example

Create an Array from a String:

Demo

var myArr = Array.from("ABCDEFG");
console.log( myArr);

Result

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() :

Demo

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); 
});

Result

Here, we passed into the function the customer object, and in turn it returns an array formed from the individual elements.

Syntax

Array.from syntax:

Array.from(arrayLike[, mapFn[, thisArg]]) 
  • arrayLike is an array-like or iterable object and
  • mapFn, an optional argument, is a Map function that can be applied on every element of the array.
  • thisArg, optional argument, whose value is used as this when executing the mapFn.

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.