6

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.

5
  • Do you mean a[3] = "item-3"? This is not a good idea to do this though. Commented Jan 4, 2019 at 12:21
  • Why it is not good idea to do ? I mean of course there will be undefined items but other than that is there any bad side ? @YeldarKurmangaliyev Commented Jan 4, 2019 at 12:33
  • Possible duplicate of How to insert an item into an array at a specific index? Commented Jan 4, 2019 at 12:37
  • 2
    @ysnfrk Because this is not how an array is supposed to be used. If you do var a = []; a[100000] = true;, then a.length will be 100001. Also, most of algorithms rely on this length, which can cause many problems. Just use object \ set if you need key-value association array. Commented Jan 4, 2019 at 14:29
  • @ysnfrk have you got any approach for this. I would like to know about it. Commented Jun 5, 2021 at 8:51

3 Answers 3

18

Just use the index and do the assignment directly:

var a = [];

a[3] = "item-3";

console.log(a);

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

1 Comment

(As always: Hope my edit is helpful, but if not, please revert it.)
6

Coming in for the ES6 solution:

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

Comments

0

Assign the value to the index like this:

var a = [];

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

console.log(a);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.