I'm trying to efficiently write a statement that pushes to position 1 of an array, and pushes whatever is in that position, or after it back a spot.
array = [4,5,9,6,2,5]
#push 0 to position 1
array = [4,0,5,9,6,2,5]
#push 123 to position 1
array = [4,123,0,5,9,6,2,5]
What is the best way to write this? (javascript or coffeescript acceptable)
Thanks!
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]
splice() function is the only native array function that lets you add elements to the specific place of an arrayI 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
numberOfItemsToRemoveto 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 addfunction 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>
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