165

in javascript how would I create an empty array of a given size

Psuedo code:

X = 3;
createarray(myarray, X, "");

output:

   myarray = ["","",""]
3
  • 5
    You'd probably use Array.prototype.fill. Commented Jan 22, 2016 at 1:17
  • Possible duplicate of default array values Commented Jun 27, 2017 at 0:20
  • Related post here. Commented Oct 9, 2017 at 0:54

9 Answers 9

397

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]

Sign up to request clarification or add additional context in comments.

8 Comments

Array.prototype.fill (>=ES6) kangax.github.io/compat-table/es6/…;
Enlightenment of the day - when you mention in part (A) that a newly created array using constructor syntax is not even iteratable. Javascript really surprises at times.
What is the size of Array(10000) with empty x 10000?
Its length is 10000, you can check it by console.log(Array(10000).length) But if you run Array(10000).forEach((u, i) => console.log(i)), you will get no output
Someone please explain 1). Why can't you iterate?
Because 1) creates a sparse array
|
102
var arr = new Array(5);
console.log(arr.length) // 5

3 Comments

The OP asked in javascript how would I create an empty array of a given size. This solves that problem.
The OP has provided an example of "empty".
Well this is another option to the question. They can choose any of the answers provided, that's the glory of stackoverflow :)
63

We use Array.from({length: 500}) since 2017.

3 Comments

@gion_13: I see it being voted up and mine being voted down. Reason?
@7vujy0f0hy I don’t know why you got down votes. I gave you an up vote, although your solution is a bit less intuitive than this one.
@gion_13: Thanks for confirming there’s nothing wrong with my solution ☺.
35

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('');

5 Comments

new Array(2) doesn't give you [undefined, undefined]. It gives you an array that isn't iterable.
OK. There's something else going on I don't understand. I'm creating a new array with new Array(2) and what I get back is [ <2 empty items> ] not [undefined, undefined]. Using .map on the former has no effect. However, I can iterate over it using a for...of loop. If I create a new array using literal notation a = [undefined, undefined] then I can use .map on it.
@JCF for...of uses iterator protocol, so it behaves differently than forEach/map. Iterators loose emptiness information
@TomaszBłachut @JCF For the down-voters, please keep in mind that this answer was given over 4 years ago – at which time, this answer was 100% valid. ES6 and ES7 did not start rolling out to browsers until mid-2016 and mid-2018, respectively. At the time of this answer, the JS version would have been ES5. If you need further proof that this is the way ES5 worked, simply spin up an older instance of Chrome – at the time of this answer, it would have been v48 – and run Array(5). You will see the following output: [undefined x 5].
@jeffdill2 It's best to add new information to the answer itself. The comments are not always fully read.
24

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("");

1 Comment

.fill() is an elegant one liner solution. Thanks!
20

In 2018 and thenceforth we shall use [...Array(500)] to that end.

3 Comments

into the future!
Hilariously this (and similar) is 50% slower than just (() => { let n = []; for(var i=0;i<500;i++){y.push("");} return n; })().
That reeks of premature optimization, maybe if you're intending to create a bunch of arrays with tens of millions of elements you might want to consider it but a few nanoseconds, for most cases, isn't going to make it worth the readability hit.
6

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)

Comments

1

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>

Comments

1

I've created benchmark tests for generating the empty arrays for iteration. The spread operator is the fastest. Array.from({length:n}) is the slowest.

  • Array.apply(null, Array(n)).map()
  • [...Array(n)].map()
  • Array(n).fill(null).map()
  • Array.from({ length: n }).map()
  • Array.from({ length:n }, (item, i) => i)

https://www.measurethat.net/Benchmarks/Show/25596/1/compare-the-ways-to-generate-an-empty-array-for-iterati enter image description here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.