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.
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.
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.
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.
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).
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"]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With