GAZAR

Principal Engineer | Mentor

Exploring Array.from() in TypeScript

Exploring Array.from() in TypeScript

The Array.from() method creates a new, shallow-copied array instance from an array-like or iterable object. In TypeScript, this method becomes even more powerful due to its compatibility with various data structures and functions.

Array.from(arrayLike [, mapFunction [, thisArg]])
const arr = Array.from(Array(3), () => 0);
console.log(arr); // Output: [0, 0, 0]

or in the more complex answer, you can set them all in a 2d array to 0

const arr = Array.from(Array(2), () => Array.from(new Array(4),() => 0));

Understanding Array.from() opens up a plethora of possibilities for array manipulation in TypeScript. Whether you’re creating arrays with default values or generating complex data structures, Array.from() proves to be an invaluable tool in your TypeScript arsenal.