JavaScript Array.from() method
The Array.from()
method in JavaScript creates a new array from an array-like or iterable object (such as strings, sets, maps, or arguments objects). It also allows for an optional mapping function to modify elements during the creation of the new array.
Syntax:
arrayLike
: The array-like or iterable object to convert to an array.mapFn
(optional): A map function to apply to each element before adding it to the new array.thisArg
(optional): The value to use asthis
when executing the map function.
Description:
Array.from()
can turn any array-like object (e.g.,arguments
,NodeList
) or iterable (e.g., strings, sets) into a real array.- You can optionally provide a mapping function, similar to
Array.prototype.map()
, to apply to each element before returning the final array. - If the object is not iterable or array-like,
Array.from()
will throw an error.
Examples:
1. Convert a string to an array:
2. Convert a set to an array:
3. Convert an arguments object to an array:
4. Using a mapping function:
5. Convert an iterable (e.g., a map) to an array:
6. Convert a NodeList to an array:
If you have a list of DOM elements (e.g., from document.querySelectorAll()
), you can convert that to an array:
Array-like Objects vs. Iterables:
- Array-like objects: Objects that have a
length
property and indexed elements, likearguments
or a DOMNodeList
. - Iterables: Objects that can be iterated over, such as strings, sets, maps, etc.
Summary:
Array.from()
is useful when you need to create a true array from array-like objects or iterables.- It provides a concise and reliable way to convert data structures to arrays and offers an optional mapping function to process elements as they're added to the new array.