Created
September 12, 2016 09:39
-
-
Save KarateJB/49731dfccfee0c8976e71a198947f007 to your computer and use it in GitHub Desktop.
[JS] Move element in array
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.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