An Interest In:
Web News this Week
- April 2, 2024
- April 1, 2024
- March 31, 2024
- March 30, 2024
- March 29, 2024
- March 28, 2024
- March 27, 2024
December 18, 2022 10:00 am GMT
Original Link: https://dev.to/trinityyi/javascript-arrayfrom-second-argument-16b9
Javascript Array.from() second argument
Array.from()
is a method that creates a new array from an array-like or iterable object. However, one property that is often overlooked is that the method can accept a mapping function as a second argument.
This map function is called on every element of the array that is being generated. Basically, Array.from()
with a function as a second argument is equivalent to Array.from().map()
only that it does not create an intermediate array.
console.log(Array.from([1, 2, 3], x => x + x)); // [2, 4, 6]
One very simple use case for this is to create an array of a specific length and fill it with an arithmetic sequence.
For example, if you want to create an array of 5 elements and fill it with the value 1 to 5, you can do it like this:
const arr = Array.from({ length: 5 }, (v, i) => i + 1);console.log(arr); // [1, 2, 3, 4, 5]
Original Link: https://dev.to/trinityyi/javascript-arrayfrom-second-argument-16b9
Share this article:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To