javascript create empty array of a given size
JavascriptJavascript Problem Overview
in javascript how would I create an empty array of a given size
Psuedo code:
X = 3;
createarray(myarray, X, "");
output:
myarray = ["","",""]
Javascript Solutions
Solution 1 - Javascript
1) To create new array which, you cannot iterate over, you can use array constructor:
Array(100)
or new Array(100)
2) You can create new array, which can be iterated over like below:
a) All JavaScript versions
- Array.apply:
Array.apply(null, Array(100))
b) From ES6 JavaScript version
- Destructuring operator:
[...Array(100)]
- Array.prototype.fill
Array(100).fill(undefined)
- Array.from
Array.from({ length: 100 })
You can map over these arrays like below.
-
Array(4).fill(null).map((u, i) => i)
[0, 1, 2, 3] -
[...Array(4)].map((u, i) => i)
[0, 1, 2, 3] -
Array.apply(null, Array(4)).map((u, i) => i)
[0, 1, 2, 3] -
Array.from({ length: 4 }).map((u, i) => i)
[0, 1, 2, 3]
Solution 2 - Javascript
var arr = new Array(5);
console.log(arr.length) // 5
Solution 3 - Javascript
We use Array.from({length: 500})
since 2017.
Solution 4 - Javascript
As of ES5 (when this answer was given):
If you want an empty array of undefined
elements, you could simply do
var whatever = new Array(5);
this would give you
[undefined, undefined, undefined, undefined, undefined]
In newer versions, this now gives
[empty × 5]
See this other question on the difference between empty and undefined.
If you wanted it to be filled with empty strings, you could do
whatever.fill('');
which would give you
["", "", "", "", ""]
And if you want to do it in one line:
var whatever = Array(5).fill('');
Solution 5 - Javascript
Try using while
loop, Array.prototype.push()
var myArray = [], X = 3;
while (myArray.length < X) {
myArray.push("")
}
Alternatively, using Array.prototype.fill()
var myArray = Array(3).fill("");
Solution 6 - Javascript
In 2018 and thenceforth we shall use [...Array(500)]
to that end.
Solution 7 - Javascript
If you want to create anonymous array with some values so you can use this syntax.
var arr = new Array(50).fill().map((d,i)=>++i)
console.log(arr)
Solution 8 - Javascript
You can use both javascript methods repeat() and split() together.
" ".repeat(10).split(" ")
This code will create an array that has 10 item and each item is empty string.
const items = " ".repeat(10).split(" ")
document.getElementById("context").innerHTML = items.map((item, index) => index)
console.log("items: ", items)
<pre id="context">
</pre>