Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to push to an array in a particular position?

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!

like image 684
fancy Avatar asked Sep 09 '25 18:09

fancy


2 Answers

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]
like image 54
fancy Avatar answered Sep 12 '25 08:09

fancy


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 item
  • numberOfItemsToRemove = 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>

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!