How to use Array.from() Method In Javascript
In ES6, we got something new called JavaScript Array.from() function, by which we can create an array of a given size.
Example: In this example, we are using Array.from() method for creating an array.
let arr = Array.from(Array(5));
console.log(arr.length);
console.log(arr);
Output:
5
[undefined, undefined, undefined, undefined, undefined]
Example 2: In this example, we will pass the elements as arguments, each character will be an array element
let arr = Array.from('w3wiki');
console.log(arr.length);
console.log(arr)
Output:
13
["G", "E", "E", "K", "S", "F", "O", "R", "G", "E", "E", "K", "S"]
Example 3: In this example, we will pass a single element as a parameter and repeat the length we want in our array.
let arr = Array.from('G'.repeat(5));
console.log(arr.length);
console.log(arr);
Output:
5
["G", "G", "G", "G", "G"]
Example 4: In this method, we will use two features of ES6, one JavaScript Array.from() function and the arrow function to create an array with a given size.
let arr = Array.from({ length: 5 }, (x, i) => i);
console.log(arr.length);
console.log(arr)
Output:
5
[0, 1, 2, 3, 4]
Create an array of given size in JavaScript
Creating an array of a specific size can be achieved through various methods, each suited to different situations. In this article, we will explore several approaches to creating arrays of a desired size, accompanied by examples for each method.
Below are the following ways:
Table of Content
- Using JavaScript array() constructor
- Using apply() and map() Methods
- Using JavaScript Array.from() Method
- Using for loop
- Using the spread syntax with Array.fill()