How to insert an item into an empty array at a specific index?

Viewed 6049

I want to insert a item to specified index of an empty Array. I saw there is Array.prototype.splice method. However, if I use splice on empty Array, it just add item to end off Array as shown below.

var a = [];
a.splice(3,0,"item-3");
console.log(a); //returns ['item-3']

What I want to accomplish is to have array as given below.

console.log(a); //returns [,,,'item-3']
or
console.log(a); //returns [undefined,undefined,undefined,'item-3']

Thanks for your help.

Edit: I saw the question on How to insert an item into an array at a specific index? but, it did not explain how to insert to specified index of empty array.

3 Answers

Just use the index and do the assignment directly:

var a = [];

a[3] = "item-3";

console.log(a);

Coming in for the ES6 solution:

[...Array(3), 'item-3']
// [undefined, undefined, undefined, "item-3"]

Assign the value to the index like this:

var a = [];

a[3] = "item-3"; //3 is the index

console.log(a);

Related