Developed By
Gautam Kumar - Full stack developer
DEEP DIVE INTO
The Array.from()
method is a built-in method in JavaScript used to create a new array from an iterable object or an array-like structure.
In this deep dive, we'll explore the Array.from()
method in detail, including its usage, behavior, and considerations.
javascriptArray.from(iterable[, mapFunction[, thisArg]]);
iterable: The object to create an array from.
mapFunction (optional): A function to map elements from the iterable.
thisArg (optional): The value to use as this when executing mapFunction.
Array.from()
returns a new array created from the elements of the provided iterable or array-like object.
Creating an Array from a String:
javascriptconst str = 'Hello';
const charArray = Array.from(str);
console.log(charArray); // Outputs: ['H', 'e', 'l', 'l', 'o']
In this example, the Array.from()
method is used to create a new array, charArray, containing the individual characters of the string str.
Mapping Elements:
javascriptconst numbers = [1, 2, 3];
const doubled = Array.from(numbers, (number) => number * 2);
console.log(doubled); // Outputs: [2, 4, 6]
Here, the Array.from() method is used to create a new array, doubled, by mapping each element of the numbers array and doubling it using the provided mapping function.
Using a Set:
javascriptconst set = new Set([1, 2, 3, 2, 1]);
const uniqueArray = Array.from(set);
console.log(uniqueArray); // Outputs: [1, 2, 3]
In this case, Array.from()
is used to create an array, uniqueArray, from a Set to remove duplicate values.
Using thisArg:
javascriptconst numbers = [1, 2, 3];
const sum = 5;
const mappedArray = Array.from(numbers, function (number) {
return number + this.sum;
}, { sum });
console.log(mappedArray); // Outputs: [6, 7, 8]
Here, Array.from()
is used with a mapping function that references this.sum to add a value to each element. The thisArg parameter specifies the context object with the sum property.
The Array.from()
method works with any iterable object, including arrays, strings, sets, maps, and array-like objects.
When mapFunction is provided, it can be used to transform each element during array creation.
The original iterable or array-like object remains unchanged.
The Array.from()
method has a time complexity of O(N), where N is the number of elements in the iterable or array-like object. It needs to iterate through the elements to create the new array.
In summary, the Array.from()
method is a powerful tool for creating new arrays from iterable objects and array-like structures. It's versatile and allows for element mapping during array creation. This method is useful for various data transformation tasks and working with different types of iterable data sources.