How to use apply() and map() Methods In Javascript
We will use apply() and map() methods to create an array with the given size. It will create an array without any value with a given size. But the values of the array will be undefined.
Example 1: In this example, we are using the apply() and map() method for creating an array.
let arr = Array.apply(null, Array(5))
.map(function () { });
console.log(arr.length);
console.log(arr);
Output:
5
[undefined, undefined, undefined, undefined, undefined]
Example 2: We will put the values of the indexes so it will give you an array of length 5 and its values will be the index number 0, 1, 2, 3, 4.
let arr = Array.apply(null, Array(5))
.map(function (y, i) { return 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()