The Array.from()
method is used to create a new array from an array-like or iterable object. It provides an easy way to convert objects like strings, sets, maps, or node lists into a proper array.
Syntax
Array.from(arrayLike, mapFunction, thisArg);
Parameters
Parameter | Description |
---|---|
arrayLike | (Required) The array-like or iterable object to be converted into an array. |
mapFunction | (Optional) A function to call on every element of the array, similar to Array.prototype.map() . |
thisArg | (Optional) A value to use as this when executing the mapFunction . If not provided, it defaults to undefined . |
Return Value
The Array.from()
method returns a new array populated with elements from the provided arrayLike
object. If a mapFunction
is provided, the resulting array elements are the result of calling the mapFunction
on each element.
Example 1: Converting a String to an Array
let str = "hello"; let arr = Array.from(str); console.log(arr); // Output: ['h', 'e', 'l', 'l', 'o']
Example 2: Using mapFunction
for Transformation
let numbers = Array.from([1, 2, 3], num => num * 2); console.log(numbers); // Output: [2, 4, 6]
Here, the mapFunction
multiplies each element of the input array by 2 while creating the new array.
Example 3: Converting a Set
to an Array
let mySet = new Set([10, 20, 30]); let arr = Array.from(mySet); console.log(arr); // Output: [10, 20, 30]
Example 5: Creating Arrays with Custom Lengths
let arr = Array.from({ length: 5 }, (_, i) => i + 1); console.log(arr); // Output: [1, 2, 3, 4, 5]
Here, Array.from()
is used to create an array of length 5, where each element is the index plus 1.
Supported Browsers
Browser | Support |
---|---|
Chrome | 45+ |
Firefox | 32+ |
Safari | 9+ |
Edge | 12+ |
Opera | 32+ |
Internet Explorer | Not supported (requires polyfill) |
Note:
The Array.from()
method was introduced in ECMAScript 6 (ES6) and is widely supported in modern browsers. For compatibility with older browsers like Internet Explorer, a polyfill is necessary.