Created
April 2, 2014 12:35
-
-
Save varemenos/9933199 to your computer and use it in GitHub Desktop.
Function to move an Array item to another position of that 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
var t = [ 'a', 'b', 'c', 'd', 'e']; | |
Array.prototype.move = function (source, destination) { | |
// if source and destination are the same | |
if (source === destination) { | |
// then there is no need to move | |
return; | |
} | |
// if the source is smaller than 0 or the destination is larger than the size of the array | |
if (source < 0 || source > this.length - 1 || destination > this.length - 1) { | |
// then the statement is invalid | |
throw new RangeError('The \'source\' or \'destination\' parameters are out of range'); | |
} | |
var value2move = this[source]; | |
this.splice(source, 1); | |
this.splice(destination, 0, value2move); | |
}; | |
t.move(4, 0); | |
console.log(t); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment