• JavaScript Video Tutorials

JavaScript - Array .from() Method



In JavaScript, the Array.from() method is a static method. It creates a new, shadow-copied array from an array-like object or iterable object. This method allows us to convert objects that are not array (such as strings, sets, or array-like objects) into arrays.

Since the Array.from() method is a static property of the JavaScript Array object, we can only use it as Array.from(). If we use this method as number.from(), where number is an array, it will return 'undefined'.

Syntax

Following is the syntax of JavaScript Array.from() method −

Array.from(arrayLike, mapFn, thisArg)

Parameters

This method accepts three parameters. The same is described below −

  • arrayLike − An array-like or iterable object to convert to an array.
  • mapFn (optional) − A mapping function to call on each element.
  • thisArg (optional) − The value to use as this when executing mapFn.

Return Value

This method returns a new Array instance.

Examples

Example 1

In the following example, we are converting a "string" to an array of characters using JavaScript Array.from() method.

<html>
<body>
   <script>
      const str = 'Tutorialspoint';
      const arr = Array.from(str);
      document.write(arr);
   </script>
</body>
</html>

After executing the above program, it converts string "str" into an array of its characters.

Output

T,u,t,o,r,i,a,l,s,p,o,i,n,t

Example 2

In this example, we are creating an array from an "array-like object", which has a length property and numeric properties like an array −

<html>
<body>
   <script>
      const arrayLikeObj = { 0: 'apple', 1: 'banana', 2: 'cherry', length: 3 };
      const arr = Array.from(arrayLikeObj);
      document.write(arr);
   </script>
</body>
</html>

If we execute the above program, it creates an array from the array-like object 'arrayLikeObj'

Output

apple,banana,cherry

Example 3

Here, we are creating an array from a "Set" using the Array.from() method −

<html>
<body>
   <script>
      const set = new Set(['apple', 'banana', 'cherry']);
      const arr = Array.from(set);
      document.write(arr);
   </script>
</body>
</html>

As we can see in the output, the new array contains all the values from the set as elements, in the same order.

Output

apple,banana,cherry

Example 4

In the example below, we are creates an array of length 5, and the second argument (mapping function) multiplies each index i by 2 to generate the values of the array.

<html>
<body>
   <script>
      const arr = Array.from({ length: 5 }, (v, i) => i * 2);
      document.write(arr);
   </script>
</body>
</html>

Output

0,2,4,6,8
Advertisements