Created
October 25, 2019 22:22
-
-
Save donnaken15/74ca52bf755a54b5cf359a26d490d014 to your computer and use it in GitHub Desktop.
Insert and remove elements at positions in an Array in Javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Use as follows:
yourarray = ['a', 'b', '1', 'c', 'd', 'e', 'f']
yourarray.remove(2);
yourarray = ['a', 'b', 'd', 'e', 'f']
yourarray.insert(2, 'c');