Array from method

The Array from allows us to create a JavaScript array from any array-like or iterable object. It also allows us to transform the array using the map function. This tutorial lets us explore the array from method in detail.

Array from method

The Array from is a built-in Javascript method that creates a new array from the elements of an array-like or iterable object.

The Array from is a static method.

The order of elements in the newly created array is the same as the order of the elements in the original object.

The elements are shallowly copied.

Syntax

Parameters

Arraylike is an object that you want to convert to an array. The object must be an iterable object or an array-like object.

An iterable object is anything we can iterate over item by item. For example, arrays, objects, strings, Map, Set, or generator functions are iterable in JavaScript. Iterables in JavaScript implement the iterable protocol.

An array-like object is an object that has a length property and indexed elements. 

mapFunc is an optional function that we can use to transform the elements of the converted array. The from method invokes the Map function for each array element and creates a new array.

thisArg is the value that the mapFunc function uses as this.  

Array from examples

The code below creates an array from string. Note that the strings are iterables. The code below iterates over its characters and creates an array.

Array from a Set

The JavaScript Set is another example of iterables. Hence we can use array from method to convert it into an array.

Array from a Map

Array from a Array like objects

The person object in the following code is an array-like object. It has a length property and indexed elements. We can convert it into an array using Array from method.

Using mapFn to convert elements

The code below creates a new array from an existing array. We also use the mapFn to double each element of the array. The final array is the original, with each element multiplied by 2.

Note that mapFn runs after from method converts the given iterable to an array.

Summary

The Array from method creates a new array from the elements of array-like or iterable objects like map, set, arrays, strings etc.

You can transform mapFunc  a function that you can use to manipulate the elements of the original object before they’re added to the new array

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top