Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
December 18, 2022 10:00 am GMT

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:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To