Welcome to %s forums

<No. 1 Community for developers, by developers/>

Login Register

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

Get support on JavaScript,jQuery, AJAX and other related technology.
Post Reply
admin
Site Admin
Posts: 45

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

Post by admin » Wed Oct 16, 2019 10:55 pm

You can implement the Array.insert method by doing this:

Code: Select all

Array.prototype.insert = function ( index, item ) {
    this.splice( index, 0, item );
};
Then you can use it like:

Code: Select all

var arr = [ 'A', 'B', 'D', 'E' ];
arr.insert(2, 'C');

// => arr == [ 'A', 'B', 'C', 'D', 'E' ]

Post Reply