The JavaScript Array.from() method creates a new array instance from an array-like or iterable object. It provides a versatile way to convert other objects to arrays and can include a mapping function for customization.
Syntax
Array.from(arrayLike, [mapFn], [thisArg])
Parameters
Parameters | Description |
---|---|
arrayLike | Required. An array-like or iterable object to convert to an array. |
mapFn | Optional. A map function to call on every element of the array. |
thisArg | Optional. Value to use as this when executing mapFn . |
Return Value
Array Object: Returns a new array instance from the provided array-like or iterable object. If mapFn
is provided, it is called on each element before adding it to the new array.
Example 1: Converting a String to an Array
This code converts a string to an array, with each character as an element.
let str = "hello"; let arr = Array.from(str); console.log(arr);
Output:
[ "h", "e", "l", "l", "o" ]
Example 2: Converting a Set to an Array
This code converts a set of numbers to an array.
let set = new Set([1, 2, 3]); let arr = Array.from(set); console.log(arr);
Output:
[ 1, 2, 3 ]
Example 3: Using Array.from() with a Mapping Function
This code creates an array from a string and transforms each character to uppercase using a mapping function.
let str = "hello"; let arr = Array.from(str, char => char.toUpperCase()); console.log(arr);
Output:
[ "H", "E", "L", "L", "O" ]
Example 4: Creating an Array from an Arguments Object
This code converts the arguments
object to an array inside a function.
function arrayFromArgs() { let arr = Array.from(arguments); console.log(arr); } arrayFromArgs(1, 2, 3, 4);
Output:
[ 1, 2, 3, 4 ]
Example 5: Creating an Array with a Mapping Function and thisArg
This code demonstrates using Array.from()
with a mapping function and a thisArg
.
let obj = { factor: 2, multiply(value) { return value * this.factor; } }; let arr = Array.from([1, 2, 3], obj.multiply, obj); console.log(arr);
Output:
[2, 4, 6]
Supported Browsers
Chrome | Edge | Firefox | Opera | Safari |
---|---|---|---|---|
45 | 12 | 32 | 32 | 9 |