Skip to content

Instantly share code, notes, and snippets.

@donnaken15
Created October 25, 2019 22:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save donnaken15/74ca52bf755a54b5cf359a26d490d014 to your computer and use it in GitHub Desktop.
Save donnaken15/74ca52bf755a54b5cf359a26d490d014 to your computer and use it in GitHub Desktop.
Insert and remove elements at positions in an Array in Javascript
Array.prototype.remove = function(index) {
delete this[index];
for (var i = index + 1; i < this.length; i++)
this[i-1] = this[i];
this.pop();
}
Array.prototype.insert = function(index, value) {
this.unshift(undefined);
for (var i = 0; i < index + 1; i++)
this[i-1] = this[i];
this[index] = value;
}
@donnaken15
Copy link
Author

Use as follows:

yourarray = ['a', 'b', '1', 'c', 'd', 'e', 'f']
yourarray.remove(2);

yourarray = ['a', 'b', 'd', 'e', 'f']
yourarray.insert(2, 'c');

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment