JavaScript / 2 MIN READ
Array.from()
Convert array-like objects into true arrays
From the original Fervor library. Examples may use older package versions.
Exploring the Array.from() Method in JavaScript
Introduction
Welcome to the FrOnt3nd Tutorials! In this tutorial, we’ll dive into the Array.from() method in JavaScript, which allows you to create new array instances from various data sources. Whether you’re working with array-like objects or iterables, Array.from() provides a versatile way to transform and manipulate your data.
What is Array.from()?
In JavaScript, the Array.from() method is a static function that creates a new array instance from various types of data sources. These sources include array-like objects and iterable objects, which implement the iterable protocol. This method provides a convenient way to transform data and convert it into array format.
Creating Arrays from Array-like Objects
An array-like object is any object that possesses a length property and indexed elements. Using Array.from(), you can easily convert such objects into actual arrays. Let’s take a look at an example:
const myArrayLikeObj = { 0: "foo", 1: "bar", length: 2 };
const myArray = Array.from(myArrayLikeObj);
console.log(myArray); // Output: ["foo", "bar"]
In the above example, myArrayLikeObj is an object with indexed elements and a length property, making it array-like. By passing this object to Array.from(), we create a new array with the same elements as the original object.
Using the Map Function with Array.from()
The Array.from() method can also accept a second argument: a map function. This function is applied to each element in the input array during the transformation process. Let’s explore this concept with an example involving a Set object:
const mySet = new Set(["foo", "bar", "baz"]);
const myArray = Array.from(mySet, (item) => item.toUpperCase());
console.log(myArray); // Output: ["FOO", "BAR", "BAZ"]
In this example, we create a Set object containing values. By passing the mySet object to Array.from() and providing a map function, we generate a new array with each value transformed to uppercase.
Conclusion
The Array.from() method in JavaScript offers a powerful way to create arrays from various data sources. Whether you’re dealing with array-like objects or iterable objects, this method provides flexibility and functionality. By exploring the capabilities of Array.from(), you can efficiently transform and manipulate data to meet your programming needs.
Feel free to experiment further with different data sources and map functions to harness the full potential of the Array.from() method in your projects!
For more details, refer to the MDN documentation on Array.from().