Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 464
ysnfrk Avatar asked Jan 04 '19 12:01

ysnfrk


People also ask

How do you add data to an array at a specific index?

You want to explicitly add it at a particular place of the array. That place is called the index. Array indexes start from 0 , so if you want to add the item first, you'll use index 0 , in the second place the index is 1 , and so on. To perform this operation you will use the splice() method of an array.

How do I insert an item into an object at a specific index?

Use the insert() function(inserts the provided value at the specified position) to insert the given item at the first position(index=0) into the list by passing the index value as 0 and the item to be inserted as arguments to it.

How do you add an element to an empty array?

By creating a new array:Create a new array of size n+1, where n is the size of the original array. Add the n elements of the original array in this array. Add the new element in the n+1 th position. Print the new array.

How do you insert an item into an array at a specific index in Javascript?

You want the splice function on the native array object. arr.splice(index, 0, item); will insert item into arr at the specified index (deleting 0 items first, that is, it's just an insert).


2 Answers

Just use the index and do the assignment directly:

var a = [];

a[3] = "item-3";

console.log(a);
like image 94
Nina Scholz Avatar answered Oct 14 '22 17:10

Nina Scholz


Coming in for the ES6 solution:

[...Array(3), 'item-3']
// [undefined, undefined, undefined, "item-3"]
like image 25
Simon Márton Avatar answered Oct 14 '22 19:10

Simon Márton