Array.from()
The Array.from()
static method in JavaScript creates a new, shallow-copied array instance from an array-like or iterable object. It can also take an optional mapping function to transform the elements before they are added to the new array.
Syntax
Array.from(arrayLike)
Array.from(arrayLike, mapFn)
Array.from(arrayLike, mapFn, thisArg)
Parameters
Parameter | Description |
---|---|
arrayLike | An array-like or iterable object to convert into an array. |
mapFn | (Optional) A function to execute on each element of the array-like object before adding it to the new array. |
thisArg | (Optional) A value to use as this when executing the mapFn . |
Return Value
The Array.from()
method returns a new array instance that contains all elements from the array-like or iterable object, optionally modified by the mapping function.
Examples
1. Converting an Array-Like Object
This example converts a string (an array-like object) into an array.
const string = "hello";
const result = Array.from(string);
console.log(result);
Output
["h", "e", "l", "l", "o"]
Array.from(string)
converts each character of the string into an array element.
2. Using a Mapping Function
The mapFn
parameter allows transformation of elements during conversion.
const numbers = { 0: 1, 1: 2, 2: 3, length: 3 };
const result = Array.from(numbers, x => x * 2);
console.log(result);
Output
[2, 4, 6]
- The object
numbers
is treated as array-like due to its numeric indices andlength
. - The mapping function multiplies each element by 2 before adding it to the new array.
3. Converting a Set to an Array
This example demonstrates how to convert a Set
into an array using Array.from()
.
const mySet = new Set([1, 2, 3]);
const result = Array.from(mySet);
console.log(result);
Output
[1, 2, 3]
The elements of the Set
are added to the new array.
4. Using thisArg
in a Mapping Function
The thisArg
parameter is used as the context for the mapping function.
const multiplier = {
factor: 3,
};
const numbers = [1, 2, 3];
const result = Array.from(numbers, function (x) {
return x * this.factor;
}, multiplier);
console.log(result);
Output
[3, 6, 9]
- The mapping function uses
this.factor
to multiply each element. - The
thisArg
sets the context ofthis
to themultiplier
object.
5. Creating an Array from a Range of Numbers
Using Array.from()
, you can create an array from a range of numbers.
const range = Array.from({ length: 5 }, (_, i) => i + 1);
console.log(range);
Output
[1, 2, 3, 4, 5]
The range is created by mapping indices to values using the mapping function.