JavaScript Array.from()
Array.from() lets you create array object from any object with a length property or any iterable object. It is a static method and hence it is not on prototype
.
Syntax
Array.from(object, mapFunction, thisValue)
object
is an array-like object or iterable. Array-like objects can be String, Map, Set, etc.
mapFunction
is the function which will be called on every item of the array. It is an optional parameter.
thisValue
is the value to be used as this
when executing mapFunction
. It is also an optional parameter.
Let's see few applications of Array.from():
1. Converting string to array
Array.from("Hello!"); // ['H','e','l','l','o','!']
2. Creating array of numbers with specified length
const numArray = Array.from({ length: 50 },(_, index)=>{
return index;
});
console.log(numArray); // [0, 2, 3,....49]
Here, first we created an object with length property and passed a value 50. Next, a function is passed which simply returns the index which ultimately serves as the element of our array. Had we not passed this function, the resulting array would be an array of length 50, but with all the elements as undefined
.
3. Creating a deep copy of an array
const num = [1, 2, 3];
const numCopy = Array.from(num);
num === numCopy; // => false