Javascript - Insert at any index in an array

javascript

There is no straightforward API to insert in an array at any index in Javascript. Through splice API, it can be simulated as:

// extending the Array
Array.prototype.insert = function(i, e) {
  this.splice(i, 0, e)
}

In action

a = [2]

// insert 1 at 0th position
a.insert(0, 1)

// insert 3 at 2th position
a.insert(2, 3)

// insert 5 at 5th position
// wil it be error -> run it?
a.insert(5, 5)

Repl it

Check out script.js file.

Be Updated

Only articles are shared on Medium