How to push to an array in a particular position?
To push any item at specific index in array use following syntax
// The original array
var array = ["one", "two", "four"];
// splice(position, numberOfItemsToRemove, item)
array.splice(2, 0, "three");
console.log(array); // ["one", "two", "three", "four"]
array = [4,5,9,6,2,5]
#push 0 to position 1
array.splice(1,0,0)
array = [4,0,5,9,6,2,5]
#push 123 to position 1
array.splice(1,0,123)
array = [4,123,0,5,9,6,2,5]
The splice()
function is the only native array function that lets you add elements to the specific place of an array
I will get a one array that you entered in your question to describe
splice(position, numberOfItemsToRemove, item)
position
= What is the position that you want to add new itemnumberOfItemsToRemove
= This indicate how many number of items will deleted. That's mean delete will start according to the position that new item add.
Ex = if you want to add 1 position to 123 result will be like this ([4,123,0,5,9,6,2,5]) but if you give
numberOfItemsToRemove
to 1 it will remove first element after the 123 if you give 2 then its delete two element after 123.
item
= the new item that you add
function my_func(){
var suits = [4,0,5,9,6,2,5]
suits.splice(1 , 0 , 123);
document.getElementById('demo').innerHTML = suits;
}
<p id="demo">4,0,5,9,6,2,5</p>
<button id="btn01" onclick="my_func()">Splice Array</button>