DEV Community

Cover image for Javascript Array.from() second argument
Isabelle M.
Isabelle M.

Posted on

4

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]
Enter fullscreen mode Exit fullscreen mode

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]
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay