Skip to content

Instantly share code, notes, and snippets.

@KarateJB
Created September 12, 2016 09:39
Show Gist options
  • Save KarateJB/49731dfccfee0c8976e71a198947f007 to your computer and use it in GitHub Desktop.
Save KarateJB/49731dfccfee0c8976e71a198947f007 to your computer and use it in GitHub Desktop.
[JS] Move element in array
Array.prototype.move = function (old_index, new_index) {
if (new_index >= this.length) {
var k = new_index - this.length;
while ((k--) + 1) {
this.push(undefined);
}
}
this.splice(new_index, 0, this.splice(old_index, 1)[0]);
return this; // for testing purposes
};
//Demo
var customers = [...];
customers.move(2,0); //Move the element at index: 2 to index 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment