How to use the JavaScript's Array.from() method

The Array.from() method in JavaScript is used to create a new Array object, given any array-like or iterable object.

svg viewer

Syntax

The syntax for Array.from() method is shown below:

svg viewer
  • arrayLike: An array-like or any iterable object to be converted into a new array object. This argument must be given.

  • mapFn: An optional map function argument to be applied on each element of the array being generated. Essentially, Array.from(arrayLike, mapFn, thisArg) has the same result as Array.from(arrayLike).map(mapFn, thisArg). The only difference is that it does not create an intermediate array.

  • thisArg: An optional value to be used as this by the map function, mapFn.


Examples

Here are some examples to help you better understand how to use the Array.from() method.

1. String to Array

This example shows the simple usage of Array.from() method to convert a String into an array where each character becomes an element of the array.

const str = "Educative!";
const arr = Array.from(str);
console.log(arr);

2. String to Array with Map function

This example shows how to use the map function, passed as an argument to the Array.from() method. Here, the map function x => x + '.' is meant to take each character from the string as an individual element and append a dot . to it.

const str = "Educative!";
const arr = Array.from(str, x => x + '.');
console.log(arr);

3. Set to Array

This example shows how to use the Array.from() method to convert a given Set object to an Array of its values.

const mySet = new Set([0, 200, 300, 200, 400, 401]);
const arr = Array.from(mySet);
console.log(arr);
Copyright ©2024 Educative, Inc. All rights reserved