OneCompiler

Insert Item in Array

102

Array.prototype.InsertItem=function (pos,item){

if(this.length<pos ||pos<0|| isNaN(pos))
{
throw new Error('Please enter Valid Position')
}
else if (this.length==pos)
{
this[pos]=item
}
else
{
for(let i=this.length-1;i>=pos;i--)
{
this[i+1]=this[i]
if(i==pos)
{
this[i]=item
}

  }
}

return this

}

Example -

let a=[3,56,34,74,7,24]

Method InsertItem(position,item)

a.InsertItem(3,78)