JavaScript Array Array.from() method
The Array.from()
method in JavaScript is a static method that creates a new array instance from an array-like or iterable object. This method is particularly useful for converting objects such as NodeList
, arguments
, or even other iterable collections (like sets or maps) into an array.
Syntax:
Parameters:
arrayLike
: An array-like or iterable object to convert into an array. This can be:- An array, a string, or an object with a length property (like
NodeList
). - Any iterable object (like
Set
orMap
).
- An array, a string, or an object with a length property (like
mapFunction
(optional): A mapping function that is called for each element in the array-like object. It takes three arguments:currentValue
: The current element being processed.index
(optional): The index of the current element.array
(optional): The array being constructed.
thisArg
(optional): A value to use asthis
when executing the map function.
Return Value:
- A new array instance.
Key Points:
Array.from()
creates a shallow copy of the elements from the provided array-like or iterable object.- If a mapping function is provided, it is executed on each element of the array-like object before being added to the new array.
- If the
thisArg
is provided, it will be used asthis
when executing the mapping function.
Example 1: Basic usage
Example 2: Converting a NodeList to an Array
Example 3: Using a Mapping Function
Example 4: Converting a Set to an Array
Example 5: Using thisArg
with a Mapping Function
Summary:
- The
Array.from()
method is a versatile tool for converting array-like or iterable objects into arrays in JavaScript. - It allows for optional mapping, enabling transformation during the conversion process.
- This method is useful in various contexts, especially when dealing with DOM elements, strings, and collections, simplifying the process of working with such data structures.